Rewriting testing utilities to use jupiter engine (#881)

* Rewriting testing utilities to use jupiter engine

Signed-off-by: Jeroen van Erp <jeroen@hierynomus.com>

* Fixed unit tests

* Fixed integration tests

---------

Signed-off-by: Jeroen van Erp <jeroen@hierynomus.com>
This commit is contained in:
Jeroen van Erp
2023-07-18 23:45:41 +02:00
committed by GitHub
parent ec69d109e8
commit 31d156b19f
64 changed files with 671 additions and 620 deletions

View File

@@ -1,7 +1,7 @@
= sshj - SSHv2 library for Java
Jeroen van Erp
:sshj_groupid: com.hierynomus
:sshj_version: 0.32.0
:sshj_version: 0.36.0
:source-highlighter: pygments
image:https://github.com/hierynomus/sshj/actions/workflows/gradle.yml/badge.svg[link="https://github.com/hierynomus/sshj/actions/workflows/gradle.yml"]
@@ -108,6 +108,12 @@ Issue tracker: https://github.com/hierynomus/sshj/issues
Fork away!
== Release history
SSHJ 0.36.0 (2023-07-14)::
* Merged https://github.com/hierynomus/sshj/pull/874[#874]: Java 8 minimum version + dependency upgrades
* Merged https://github.com/hierynomus/sshj/pull/876[#876]: Change `newStatefulSFTPClient` to return `StatefulSFTPClient`
* Merged https://github.com/hierynomus/sshj/pull/860[#860]: Upgrade to Gradle 7.6.1
* Merged https://github.com/hierynomus/sshj/pull/838[#838]: Replaced Curve25519 class with X25519 Key agreement
* Merged https://github.com/hierynomus/sshj/pull/772[#772]: Remove dependency on jzlib
SSHJ 0.35.0 (2023-01-30)::
* Merged https://github.com/hierynomus/sshj/pull/835[#835]: TimeoutException message improved
* Merged https://github.com/hierynomus/sshj/pull/815[#815]: Support authPassword on FreeBSD

View File

@@ -1,25 +1,27 @@
plugins {
id "java"
id "jvm-test-suite"
id "groovy"
id "jacoco"
id "com.github.blindpirate.osgi" version '0.0.6'
id "maven-publish"
id "signing"
id 'pl.allegro.tech.build.axion-release' version '1.13.3'
id "com.bmuschko.docker-remote-api" version "7.1.0"
id 'pl.allegro.tech.build.axion-release' version '1.15.3'
id "com.github.hierynomus.license" version "0.16.1"
id 'ru.vyarus.github-info' version '1.2.0'
id "io.github.gradle-nexus.publish-plugin" version "1.0.0"
id "com.bmuschko.docker-remote-api" version "9.2.1"
id 'ru.vyarus.github-info' version '1.5.0'
id "io.github.gradle-nexus.publish-plugin" version "1.3.0"
}
group = "com.hierynomus"
ext.moduleName = "${project.group}.${project.name}"
defaultTasks "build"
repositories {
mavenCentral()
}
group = "com.hierynomus"
defaultTasks ["build"]
ext.moduleName = "${project.group}.${project.name}"
scmVersion {
tag {
prefix = 'v'
@@ -33,6 +35,10 @@ scmVersion {
project.version = scmVersion.version
compileJava {
options.release = 8
}
configurations.implementation.transitive = false
def bouncycastleVersion = "1.75"
@@ -44,20 +50,6 @@ dependencies {
implementation "org.bouncycastle:bcpkix-jdk18on:$bouncycastleVersion"
implementation "com.hierynomus:asn-one:0.6.0"
implementation "net.i2p.crypto:eddsa:0.3.0"
testImplementation(platform("org.junit:junit-bom:5.9.3"))
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
testRuntimeOnly 'org.junit.vintage:junit-vintage-engine'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.spockframework:spock-core:2.3-groovy-3.0'
testImplementation 'org.spockframework:spock-junit4:2.3-groovy-3.0'
testImplementation "org.mockito:mockito-core:4.11.0"
testImplementation "org.apache.sshd:sshd-core:$sshdVersion"
testImplementation "org.apache.sshd:sshd-sftp:$sshdVersion"
testImplementation "org.apache.sshd:sshd-scp:$sshdVersion"
testImplementation "ch.qos.logback:logback-classic:1.3.8"
testImplementation 'org.glassfish.grizzly:grizzly-http-server:3.0.1'
testImplementation 'org.testcontainers:testcontainers:1.18.3'
}
license {
@@ -73,6 +65,11 @@ license {
])
}
java {
withJavadocJar()
withSourcesJar()
}
if (!JavaVersion.current().isJava9Compatible()) {
throw new GradleScriptException("Minimum compilation version is Java 9")
}
@@ -84,10 +81,80 @@ if (JavaVersion.current().isJava8Compatible()) {
}
}
compileJava {
options.compilerArgs.addAll(['--release', '8'])
testing {
suites {
configureEach {
useJUnitJupiter()
dependencies {
implementation "org.slf4j:slf4j-api:2.0.7"
implementation 'org.spockframework:spock-core:2.3-groovy-3.0'
implementation "org.mockito:mockito-core:4.11.0"
implementation "ru.vyarus:spock-junit5:1.2.0"
implementation "org.apache.sshd:sshd-core:$sshdVersion"
implementation "org.apache.sshd:sshd-sftp:$sshdVersion"
implementation "org.apache.sshd:sshd-scp:$sshdVersion"
implementation "ch.qos.logback:logback-classic:1.3.8"
implementation 'org.glassfish.grizzly:grizzly-http-server:3.0.1'
}
targets {
all {
testTask.configure {
testLogging {
exceptionFormat = 'full'
}
include "**/*Test.*"
include "**/*Spec.*"
afterSuite { descriptor, result ->
def indicator = "\u001B[32m✓\u001b[0m"
if (result.failedTestCount > 0) {
indicator = "\u001B[31m✘\u001b[0m"
}
logger.lifecycle("$indicator Test ${descriptor.name}; Executed: ${result.testCount}/\u001B[32m${result.successfulTestCount}\u001B[0m/\u001B[31m${result.failedTestCount}\u001B[0m")
}
}
}
}
}
test {
sources {
groovy {
srcDirs = ['src/test/groovy']
}
}
}
integrationTest(JvmTestSuite) {
dependencies {
implementation project()
implementation 'org.testcontainers:testcontainers:1.18.3'
implementation 'org.testcontainers:junit-jupiter:1.18.3'
}
sources {
groovy {
srcDirs = ['src/itest/groovy']
}
resources {
srcDirs = ['src/itest/resources']
}
}
targets {
all {
testTask.configure {
shouldRunAfter(test)
}
}
}
}
}
}
project.tasks.compileGroovy.onlyIf { false }
task writeSshjVersionProperties {
doLast {
project.file("${project.buildDir}/resources/main").mkdirs()
@@ -121,11 +188,6 @@ jar {
}
}
java {
withJavadocJar()
withSourcesJar()
}
sourcesJar {
manifest {
attributes(
@@ -139,46 +201,6 @@ sourcesJar {
}
}
configurations {
integrationTestImplementation.extendsFrom testImplementation
integrationTestRuntimeOnly.extendsFrom testRuntimeOnly
}
sourceSets {
integrationTest {
groovy {
compileClasspath += sourceSets.main.output + sourceSets.test.output
runtimeClasspath += sourceSets.main.output + sourceSets.test.output
srcDir file('src/itest/groovy')
}
resources.srcDir file('src/itest/resources')
}
}
task integrationTest(type: Test) {
testClassesDirs = sourceSets.integrationTest.output.classesDirs
classpath = sourceSets.integrationTest.runtimeClasspath
}
tasks.withType(Test) {
testLogging {
exceptionFormat = 'full'
}
useJUnitPlatform()
afterSuite { descriptor, result ->
if (descriptor.className != null) {
def indicator = "\u001B[32m✓\u001b[0m"
if (result.failedTestCount > 0) {
indicator = "\u001B[31m✘\u001b[0m"
}
logger.lifecycle("$indicator Test ${descriptor.name}; Executed: ${result.testCount}/\u001B[32m${result.successfulTestCount}\u001B[0m/\u001B[31m${result.failedTestCount}\u001B[0m")
}
}
}
project.tasks.compileGroovy.onlyIf { false }
github {
user 'hierynomus'
license 'Apache'
@@ -264,17 +286,11 @@ nexusPublishing {
jacocoTestReport {
reports {
xml.enabled true
html.enabled true
xml.required = true
html.required = true
}
}
task forkedUploadRelease(type: GradleBuild) {
buildFile = project.buildFile
tasks = ["clean", "publishToSonatype", "closeAndReleaseSonatypeStagingRepository"]
}
project.tasks.release.dependsOn([project.tasks.integrationTest, project.tasks.build])
project.tasks.release.finalizedBy(project.tasks.forkedUploadRelease)
project.tasks.jacocoTestReport.dependsOn(project.tasks.test)
project.tasks.check.dependsOn(project.tasks.jacocoTestReport)

View File

@@ -1,5 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -20,15 +20,17 @@ import net.schmizz.sshj.DefaultConfig
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.transport.TransportException
import net.schmizz.sshj.userauth.UserAuthException
import org.junit.ClassRule
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
@Testcontainers
class IntegrationSpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
@Unroll
def "should accept correct key for #signatureName"() {

View File

@@ -15,13 +15,15 @@
*/
package com.hierynomus.sshj.sftp
import com.hierynomus.sshj.IntegrationTestUtil
import com.hierynomus.sshj.SshdContainer
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.sftp.OpenMode
import net.schmizz.sshj.sftp.RemoteFile
import net.schmizz.sshj.sftp.SFTPClient
import org.junit.ClassRule
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
@@ -29,10 +31,11 @@ import java.nio.charset.StandardCharsets
import static org.codehaus.groovy.runtime.IOGroovyMethods.withCloseable
@Testcontainers
class FileWriteSpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
def "should append to file (GH issue #390)"() {
given:

View File

@@ -19,7 +19,8 @@ import com.hierynomus.sshj.SshdContainer
import net.schmizz.sshj.DefaultConfig
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import org.junit.ClassRule
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
@@ -29,10 +30,11 @@ import spock.lang.Unroll
*
* Also, take a look at the unit test {@link net.schmizz.sshj.transport.verification.KeyWithCertificateUnitSpec}.
*/
@Testcontainers
class PublicKeyAuthWithCertificateSpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
@Unroll
def "authorising with a signed public key #keyName"() {

View File

@@ -17,15 +17,17 @@ package com.hierynomus.sshj.signature
import com.hierynomus.sshj.IntegrationTestUtil
import com.hierynomus.sshj.SshdContainer
import org.junit.ClassRule
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
@Testcontainers
class RsaSignatureClientKeySpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
@Unroll
def "should correctly connect using publickey auth with RSA key with signature"() {

View File

@@ -19,15 +19,17 @@ import com.hierynomus.sshj.IntegrationTestUtil
import com.hierynomus.sshj.SshdContainer
import com.hierynomus.sshj.key.KeyAlgorithms
import net.schmizz.sshj.DefaultConfig
import org.junit.ClassRule
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
@Testcontainers
class SignatureSpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
@Unroll
def "should correctly connect with #sig Signature"() {

View File

@@ -18,15 +18,17 @@ package com.hierynomus.sshj.transport.cipher
import com.hierynomus.sshj.IntegrationTestUtil
import com.hierynomus.sshj.SshdContainer
import net.schmizz.sshj.DefaultConfig
import org.junit.ClassRule
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
@Testcontainers
class CipherSpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
@Unroll
def "should correctly connect with #cipher Cipher"() {

View File

@@ -22,15 +22,15 @@ import net.schmizz.sshj.transport.kex.Curve25519SHA256
import net.schmizz.sshj.transport.kex.DHGexSHA1
import net.schmizz.sshj.transport.kex.DHGexSHA256
import net.schmizz.sshj.transport.kex.ECDHNistP
import org.junit.ClassRule
import spock.lang.Shared
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Specification
import spock.lang.Unroll
@Testcontainers
class KexSpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
@Unroll
def "should correctly connect with #kex Key Exchange"() {

View File

@@ -18,15 +18,17 @@ package com.hierynomus.sshj.transport.mac
import com.hierynomus.sshj.IntegrationTestUtil
import com.hierynomus.sshj.SshdContainer
import net.schmizz.sshj.DefaultConfig
import org.junit.ClassRule
import org.testcontainers.junit.jupiter.Container
import org.testcontainers.junit.jupiter.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll
@Testcontainers
class MacSpec extends Specification {
@Shared
@ClassRule
SshdContainer sshd
@Container
static SshdContainer sshd = new SshdContainer()
@Unroll
def "should correctly connect with #mac MAC"() {

View File

@@ -15,18 +15,18 @@
*/
package com.hierynomus.sshj.connection.channel.direct
import com.hierynomus.sshj.test.SshFixture
import com.hierynomus.sshj.test.SshServerExtension
import net.schmizz.sshj.connection.channel.direct.Parameters
import org.junit.Rule
import org.junit.jupiter.api.extension.RegisterExtension
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
class LocalPortForwarderSpec extends Specification {
@Rule
SshFixture tunnelFixture = new SshFixture()
@RegisterExtension
SshServerExtension tunnelFixture = new SshServerExtension()
@Rule
SshFixture realServer = new SshFixture()
@RegisterExtension
SshServerExtension realServer = new SshServerExtension()
def "should not hang when disconnect tunnel"() {
given:

View File

@@ -15,25 +15,29 @@
*/
package com.hierynomus.sshj.sftp
import com.hierynomus.sshj.test.SshFixture
import com.hierynomus.sshj.test.SshServerExtension
import com.hierynomus.sshj.test.util.FileUtil
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.sftp.FileMode
import net.schmizz.sshj.sftp.SFTPClient
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import org.junit.jupiter.api.extension.RegisterExtension
import spock.lang.Specification
import spock.lang.TempDir
import spock.lang.Unroll
import java.nio.file.Files
import java.nio.file.Path
import static org.codehaus.groovy.runtime.IOGroovyMethods.withCloseable
class SFTPClientSpec extends Specification {
@Rule
public SshFixture fixture = new SshFixture()
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension()
@Rule
public TemporaryFolder temp = new TemporaryFolder()
@TempDir
public Path temp
@Unroll
def "should copy #sourceType->#targetType if #targetExists with #named name"() {
@@ -79,11 +83,11 @@ class SFTPClientSpec extends Specification {
def "should not throw exception on close before disconnect"() {
given:
File file = temp.newFile("source.txt")
File file = Files.createFile(temp.resolve("source.txt")).toFile()
FileUtil.writeToFile(file, "This is the source")
when:
doUpload(file, temp.newFile("dest.txt"))
doUpload(file, temp.resolve("dest.txt").toFile())
then:
noExceptionThrown()
@@ -147,10 +151,10 @@ class SFTPClientSpec extends Specification {
def "should not merge same name subdirs (GH #252)"() {
given:
File toto = temp.newFolder("toto")
File toto = Files.createDirectory(temp.resolve("toto")).toFile()
File tutu = mkdir(toto, "tutu")
File toto2 = mkdir(toto, "toto")
File dest = temp.newFolder("dest")
File dest = Files.createDirectory(temp.resolve("dest")).toFile()
FileUtil.writeToFile(new File(toto, "toto.txt"), "Toto file")
FileUtil.writeToFile(new File(tutu, "tototutu.txt"), "Toto/Tutu file")
FileUtil.writeToFile(new File(toto2, "totototo.txt"), "Toto/Toto file")

View File

@@ -18,17 +18,16 @@ package com.hierynomus.sshj.transport.verification
import net.schmizz.sshj.common.Buffer
import net.schmizz.sshj.transport.verification.OpenSSHKnownHosts
import net.schmizz.sshj.util.KeyUtil
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import spock.lang.Specification
import spock.lang.TempDir
import spock.lang.Unroll
import java.nio.file.Files
import java.security.PublicKey
class OpenSSHKnownHostsSpec extends Specification {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@TempDir def temp
def "should parse and verify hashed host entry"() {
given:
@@ -215,7 +214,7 @@ host1 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBL
}
def knownHosts(String s) {
def f = temp.newFile("known_hosts")
def f = Files.createFile(temp.resolve("known_hosts")).toFile()
f.write(s)
return f
}

View File

@@ -15,18 +15,18 @@
*/
package com.hierynomus.sshj.userauth.keyprovider
import com.hierynomus.sshj.test.SshFixture
import com.hierynomus.sshj.test.SshServerExtension
import net.schmizz.sshj.DefaultConfig
import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.userauth.keyprovider.KeyFormat
import org.apache.sshd.server.auth.pubkey.AcceptAllPublickeyAuthenticator
import org.junit.Rule
import org.junit.jupiter.api.extension.RegisterExtension
import spock.lang.Specification
import spock.lang.Unroll
class FileKeyProviderSpec extends Specification {
@Rule
SshFixture fixture = new SshFixture(false)
@RegisterExtension
SshServerExtension fixture = new SshServerExtension(false)
def setup() {
fixture.getServer().setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE)

View File

@@ -31,20 +31,12 @@
package net.schmizz.sshj.signature
import com.hierynomus.sshj.common.KeyAlgorithm
import spock.lang.Unroll;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import spock.lang.Specification
import spock.lang.Unroll
import java.security.KeyFactory
import java.security.PublicKey
import java.security.spec.DSAPublicKeySpec
class SignatureDSASpec extends Specification {

View File

@@ -15,10 +15,10 @@
*/
package com.hierynomus.sshj.connection.channel;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.connection.channel.direct.Session;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.IOException;
@@ -26,8 +26,8 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class ChannelCloseEofTest {
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Test
public void shouldCorrectlyHandleSessionChannelEof() throws IOException, InterruptedException {

View File

@@ -15,13 +15,13 @@
*/
package com.hierynomus.sshj.connection.channel.direct;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.SFTPClient;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
@@ -30,17 +30,17 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class CommandTest {
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@TempDir
public File temp;
@Test
public void shouldExecuteBackgroundCommand() throws IOException {
SSHClient sshClient = fixture.setupConnectedDefaultClient();
sshClient.authPassword("jeroen", "jeroen");
File file = new File(temp.getRoot(), "testdir");
File file = new File(temp, "testdir");
assertThat("File should not exist", !file.exists());
// TODO figure out why this does not really execute in the background.
Session.Command exec = sshClient.startSession().exec("mkdir " + file.getPath() + " &");

View File

@@ -16,44 +16,36 @@
package com.hierynomus.sshj.connection.channel.forwarded;
import com.hierynomus.sshj.test.HttpServer;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import com.hierynomus.sshj.test.util.FileUtil;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.LocalPortForwarder;
import net.schmizz.sshj.connection.channel.direct.Parameters;
import org.apache.sshd.server.forward.AcceptAllForwardingFilter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.io.*;
import java.net.*;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class LocalPortForwarderTest {
private static final String LOCALHOST_URL = "http://127.0.0.1:8080";
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Rule
@RegisterExtension
public HttpServer httpServer = new HttpServer();
@Before
@BeforeEach
public void setUp() throws IOException {
fixture.getServer().setForwardingFilter(new AcceptAllForwardingFilter());
File file = httpServer.getDocRoot().newFile("index.html");
File file = Files.createFile(httpServer.getDocRoot().toPath().resolve("index.html")).toFile();
FileUtil.writeToFile(file, "<html><head/><body><h1>Hi!</h1></body></html>");
}
@@ -68,7 +60,8 @@ public class LocalPortForwarderTest {
httpGetAndAssertConnectionClosedByServer(8080);
}
@Test(timeout = 10_000)
@Test
@Timeout(10_000)
public void shouldCloseConnectionWhenRemoteServerClosesConnection() throws IOException {
SSHClient sshClient = getFixtureClient();
@@ -113,7 +106,7 @@ public class LocalPortForwarderTest {
int read = inputStream.read();
// Assert input stream was closed by server.
Assert.assertEquals(-1, read);
assertEquals(-1, read);
}
}

View File

@@ -16,24 +16,25 @@
package com.hierynomus.sshj.connection.channel.forwarded;
import com.hierynomus.sshj.test.HttpServer;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import com.hierynomus.sshj.test.util.FileUtil;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.forwarded.RemotePortForwarder;
import net.schmizz.sshj.connection.channel.forwarded.SocketForwardingConnectListener;
import org.apache.sshd.server.forward.AcceptAllForwardingFilter;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.file.Files;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RemotePortForwarderTest {
private static final PortRange RANGE = new PortRange(9000, 9999);
@@ -41,16 +42,16 @@ public class RemotePortForwarderTest {
private static final String LOCALHOST_URL_FORMAT = "http://127.0.0.1:%d";
private static final InetSocketAddress HTTP_SERVER_SOCKET_ADDR = new InetSocketAddress(LOCALHOST, 8080);
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Rule
@RegisterExtension
public HttpServer httpServer = new HttpServer();
@Before
@BeforeEach
public void setUp() throws IOException {
fixture.getServer().setForwardingFilter(new AcceptAllForwardingFilter());
File file = httpServer.getDocRoot().newFile("index.html");
File file = Files.createFile(httpServer.getDocRoot().toPath().resolve("index.html")).toFile();
FileUtil.writeToFile(file, "<html><head/><body><h1>Hi!</h1></body></html>");
}

View File

@@ -15,21 +15,18 @@
*/
package com.hierynomus.sshj.keepalive;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.keepalive.KeepAlive;
import net.schmizz.keepalive.KeepAliveProvider;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.userauth.UserAuthException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
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.*;
public class KeepAliveThreadTerminationTest {
@@ -37,8 +34,8 @@ public class KeepAliveThreadTerminationTest {
private static final long STOP_SLEEP = 1500;
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Test
public void shouldNotStartThreadOnSetKeepAliveInterval() {

View File

@@ -15,7 +15,7 @@
*/
package com.hierynomus.sshj.sftp;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.ByteArrayUtils;
import net.schmizz.sshj.sftp.OpenMode;
@@ -23,9 +23,9 @@ import net.schmizz.sshj.sftp.RemoteFile;
import net.schmizz.sshj.sftp.SFTPEngine;
import net.schmizz.sshj.sftp.SFTPException;
import org.apache.sshd.common.util.io.IoUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.io.*;
import java.security.SecureRandom;
@@ -34,15 +34,15 @@ import java.util.Random;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
public class RemoteFileTest {
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@TempDir
public File temp;
@Test
public void shouldNotGoOutOfBoundsInReadAheadInputStream() throws IOException {
@@ -51,7 +51,7 @@ public class RemoteFileTest {
SFTPEngine sftp = new SFTPEngine(ssh).init();
RemoteFile rf;
File file = temp.newFile("SftpReadAheadTest.bin");
File file = new File(temp, "SftpReadAheadTest.bin");
rf = sftp.open(file.getPath(), EnumSet.of(OpenMode.WRITE, OpenMode.CREAT));
byte[] data = new byte[8192];
new Random(53).nextBytes(data);
@@ -96,7 +96,7 @@ public class RemoteFileTest {
SFTPEngine sftp = new SFTPEngine(ssh).init();
RemoteFile rf;
File file = temp.newFile("SftpReadAheadLimitTest.bin");
File file = new File(temp, "SftpReadAheadLimitTest.bin");
rf = sftp.open(file.getPath(), EnumSet.of(OpenMode.WRITE, OpenMode.CREAT));
byte[] data = new byte[8192];
new Random(53).nextBytes(data);
@@ -139,7 +139,7 @@ public class RemoteFileTest {
SFTPEngine sftp = new SFTPEngine(ssh).init();
RemoteFile rf;
File file = temp.newFile("SftpReadAheadLimitedTest.bin");
File file = new File(temp, "SftpReadAheadLimitedTest.bin");
rf = sftp.open(file.getPath(), EnumSet.of(OpenMode.WRITE, OpenMode.CREAT));
byte[] data = new byte[8192];
new Random(53).nextBytes(data);
@@ -205,7 +205,7 @@ public class RemoteFileTest {
final byte[] expected = new byte[fileSize];
new SecureRandom(new byte[] { 31 }).nextBytes(expected);
File file = temp.newFile("shouldReadCorrectlyWhenWrappedInBufferedStream.bin");
File file = new File(temp, "shouldReadCorrectlyWhenWrappedInBufferedStream.bin");
try (OutputStream fStream = new FileOutputStream(file)) {
IoUtils.copy(new ByteArrayInputStream(expected), fStream);
}
@@ -221,7 +221,7 @@ public class RemoteFileTest {
actual = baos.toByteArray();
}
assertEquals("The file should be fully read", expected.length, actual.length);
assertEquals(expected.length, actual.length, "The file should be fully read");
assertThat("The file should be read correctly",
ByteArrayUtils.equals(expected, 0, actual, 0, expected.length));
}

View File

@@ -21,9 +21,8 @@ import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.transport.random.JCERandom;
import net.schmizz.sshj.transport.random.SingletonRandomFactory;
import org.apache.sshd.server.SshServer;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -36,13 +35,8 @@ public abstract class BaseAlgorithmTest {
private SingletonRandomFactory randomFactory = new SingletonRandomFactory(new JCERandom.Factory());
private DefaultConfig config = new DefaultConfig();
@Rule
public SshFixture fixture = new SshFixture(false);
@After
public void stopServer() {
fixture.stopServer();
}
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension(false);
@Test
public void shouldVerifyAlgorithm() throws IOException {

View File

@@ -15,27 +15,25 @@
*/
package com.hierynomus.sshj.test;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.io.File;
import java.nio.file.Files;
/**
* Can be used to setup a test HTTP server
*/
public class HttpServer extends ExternalResource {
public class HttpServer implements BeforeEachCallback, AfterEachCallback {
private org.glassfish.grizzly.http.server.HttpServer httpServer;
private TemporaryFolder docRoot = new TemporaryFolder();
private File docRoot ;
@Override
protected void before() throws Throwable {
docRoot.create();
httpServer = org.glassfish.grizzly.http.server.HttpServer.createSimpleServer(docRoot.getRoot().getAbsolutePath());
httpServer.start();
}
@Override
protected void after() {
public void afterEach(ExtensionContext context) throws Exception {
try {
httpServer.shutdownNow();
} catch (Exception e) {}
@@ -45,11 +43,18 @@ public class HttpServer extends ExternalResource {
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
docRoot = Files.createTempDirectory("sshj").toFile();
httpServer = org.glassfish.grizzly.http.server.HttpServer.createSimpleServer(docRoot.getAbsolutePath());
httpServer.start();
}
public org.glassfish.grizzly.http.server.HttpServer getHttpServer() {
return httpServer;
}
public TemporaryFolder getDocRoot() {
public File getDocRoot() {
return docRoot;
}
}

View File

@@ -25,8 +25,11 @@ import org.apache.sshd.scp.server.ScpCommandFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.shell.ProcessShellFactory;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;
import org.junit.rules.ExternalResource;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.io.Closeable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.ServerSocket;
@@ -36,7 +39,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
/**
* Can be used as a rule to ensure the server is teared down after each test.
*/
public class SshFixture extends ExternalResource {
public class SshServerExtension implements BeforeEachCallback, AfterEachCallback, Closeable {
public static final String hostkey = "hostkey.pem";
public static final String fingerprint = "ce:a7:c1:cf:17:3f:96:49:6a:53:1a:05:0b:ba:90:db";
public static final String listCommand = OsUtils.isWin32() ? "cmd.exe /C dir" : "ls";
@@ -46,22 +49,28 @@ public class SshFixture extends ExternalResource {
private final AtomicBoolean started = new AtomicBoolean(false);
private boolean autoStart = true;
public SshFixture(boolean autoStart) {
public SshServerExtension(boolean autoStart) {
this.autoStart = autoStart;
}
public SshFixture() {
public SshServerExtension() {
}
@Override
protected void before() throws Throwable {
public void afterEach(ExtensionContext context) throws Exception {
close();
}
@Override
public void beforeEach(ExtensionContext context) throws Exception {
if (autoStart) {
start();
}
}
@Override
protected void after() {
public void close() throws IOException {
stopClient();
stopServer();
}

View File

@@ -15,17 +15,15 @@
*/
package com.hierynomus.sshj.transport;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import com.hierynomus.sshj.transport.cipher.ChachaPolyCiphers;
import net.schmizz.sshj.common.SSHRuntimeException;
import net.schmizz.sshj.transport.cipher.Cipher;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
public class ChachaPolyCipherTest {

View File

@@ -15,30 +15,30 @@
*/
package com.hierynomus.sshj.transport;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.DisconnectListener;
import net.schmizz.sshj.transport.TransportException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class DisconnectionTest {
private AtomicBoolean disconnected = null;
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Before
@BeforeEach
public void setupFlag() throws IOException {
disconnected = new AtomicBoolean(false);
// Initialize the client

View File

@@ -20,48 +20,58 @@ import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.cipher.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.BeforeClass;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.security.Security;
import java.util.Arrays;
import java.util.stream.Stream;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* Unit test to decrypt SSH traffic with OpenSSH and Apache Mina SSHD (master) using AES-GCM ciphers, for verifying
* cipher behaviour.
*/
@RunWith(Theories.class)
public class GcmCipherDecryptSshPacketTest {
@DataPoints
public static final String sets[][] = new String[][]{{"mina-sshd", "3"}, {"openssh", "4"}};
public static Stream<Arguments> sets() {
return Stream.of(Arguments.of("mina-sshd", 3), Arguments.of("openssh", 4));
}
@BeforeClass
@BeforeAll
public static void setupBeforeClass() {
Security.addProvider(new BouncyCastleProvider());
}
@Theory
public void testDecryptPacket(String[] args) throws Exception {
@ParameterizedTest
@MethodSource("sets")
public void testDecryptPacket(String ssh, int nr) throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
byte[] iv = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/"+args[0]+"/s2c.iv.bin")).toByteArray();
byte[] key = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/"+args[0]+"/s2c.key.bin")).toByteArray();
byte[] iv = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/" + ssh + "/s2c.iv.bin"))
.toByteArray();
byte[] key = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/" + ssh + "/s2c.key.bin"))
.toByteArray();
Cipher cipher = GcmCiphers.AES128GCM().create();
cipher.init(Cipher.Mode.Decrypt, key, iv);
for(int i=1; i<=Integer.parseInt(args[1]); i++) {
byte[] data = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/"+args[0]+"/client.receive."+i+".bin")).toByteArray();
for (int i = 1; i <= nr; i++) {
byte[] data = IOUtils
.readFully(classLoader
.getResourceAsStream("ssh-packets/gcm/" + ssh + "/client.receive." + i + ".bin"))
.toByteArray();
SSHPacket inputBuffer = new SSHPacket(data);
cipher.updateAAD(inputBuffer.array(), 0, 4);
int size = inputBuffer.readUInt32AsInt();
cipher.update(inputBuffer.array(), 4, size);
byte[] expected = IOUtils.readFully(classLoader.getResourceAsStream("ssh-packets/gcm/"+args[0]+"/client.decrypted."+i+".bin")).toByteArray();
assertArrayEquals(Arrays.copyOfRange(expected, 0, size+4),
Arrays.copyOfRange(inputBuffer.array(), 0, size+4));
byte[] expected = IOUtils
.readFully(classLoader
.getResourceAsStream("ssh-packets/gcm/" + ssh + "/client.decrypted." + i + ".bin"))
.toByteArray();
assertArrayEquals(Arrays.copyOfRange(expected, 0, size + 4),
Arrays.copyOfRange(inputBuffer.array(), 0, size + 4));
}
}
}

View File

@@ -18,23 +18,21 @@ package com.hierynomus.sshj.transport;
import com.hierynomus.sshj.transport.cipher.GcmCiphers;
import net.schmizz.sshj.common.SSHRuntimeException;
import net.schmizz.sshj.transport.cipher.Cipher;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import javax.crypto.AEADBadTagException;
import java.nio.charset.StandardCharsets;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
@RunWith(Theories.class)
public class GcmCipherTest {
public static final @DataPoints
GcmCiphers.Factory[] cipherFactories = { GcmCiphers.AES128GCM(), GcmCiphers.AES256GCM() };
public static GcmCiphers.Factory[] cipherFactories() {
return new GcmCiphers.Factory[] { GcmCiphers.AES128GCM(), GcmCiphers.AES256GCM() }; };
@Theory
@ParameterizedTest
@MethodSource("cipherFactories")
public void testEncryptDecrypt(GcmCiphers.Factory factory) throws Exception {
Cipher enc = factory.create();
byte[] key = new byte[enc.getBlockSize()];

View File

@@ -15,63 +15,76 @@
*/
package com.hierynomus.sshj.transport.kex;
import com.hierynomus.sshj.test.BaseAlgorithmTest;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.Config;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.Factory;
import net.schmizz.sshj.transport.kex.DHGexSHA1;
import net.schmizz.sshj.transport.kex.DHGexSHA256;
import net.schmizz.sshj.transport.kex.ECDHNistP;
import net.schmizz.sshj.transport.random.JCERandom;
import net.schmizz.sshj.transport.random.SingletonRandomFactory;
import org.apache.sshd.common.kex.BuiltinDHFactories;
import org.apache.sshd.common.kex.KeyExchangeFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.kex.DHGEXServer;
import org.apache.sshd.server.kex.DHGServer;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Stream;
@RunWith(Parameterized.class)
public class KeyExchangeTest extends BaseAlgorithmTest {
import static org.hamcrest.MatcherAssert.assertThat;
public class KeyExchangeTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@SuppressWarnings("deprecation")
@Parameterized.Parameters(name = "algorithm={0}")
public static Collection<Object[]> getParameters() {
return Arrays.asList(new Object[][]{
{DHGEXServer.newFactory(BuiltinDHFactories.dhgex), new DHGexSHA1.Factory()},
{DHGEXServer.newFactory(BuiltinDHFactories.dhgex256), new DHGexSHA256.Factory()},
{DHGServer.newFactory(BuiltinDHFactories.ecdhp256), new ECDHNistP.Factory256()},
{DHGServer.newFactory(BuiltinDHFactories.ecdhp384), new ECDHNistP.Factory384()},
{DHGServer.newFactory(BuiltinDHFactories.ecdhp521), new ECDHNistP.Factory521()},
{DHGServer.newFactory(BuiltinDHFactories.dhg1), DHGroups.Group1SHA1()},
{DHGServer.newFactory(BuiltinDHFactories.dhg14), DHGroups.Group14SHA1()},
{DHGServer.newFactory(BuiltinDHFactories.dhg14_256), DHGroups.Group14SHA256()},
{DHGServer.newFactory(BuiltinDHFactories.dhg15_512), DHGroups.Group15SHA512()},
{DHGServer.newFactory(BuiltinDHFactories.dhg16_512), DHGroups.Group16SHA512()},
{DHGServer.newFactory(BuiltinDHFactories.dhg17_512), DHGroups.Group17SHA512()},
{DHGServer.newFactory(BuiltinDHFactories.dhg18_512), DHGroups.Group18SHA512()},
return Arrays.asList(new Object[][] {
{ DHGEXServer.newFactory(BuiltinDHFactories.dhgex), new DHGexSHA1.Factory() },
{ DHGEXServer.newFactory(BuiltinDHFactories.dhgex256), new DHGexSHA256.Factory() },
{ DHGServer.newFactory(BuiltinDHFactories.ecdhp256), new ECDHNistP.Factory256() },
{ DHGServer.newFactory(BuiltinDHFactories.ecdhp384), new ECDHNistP.Factory384() },
{ DHGServer.newFactory(BuiltinDHFactories.ecdhp521), new ECDHNistP.Factory521() },
{ DHGServer.newFactory(BuiltinDHFactories.dhg1), DHGroups.Group1SHA1() },
{ DHGServer.newFactory(BuiltinDHFactories.dhg14), DHGroups.Group14SHA1() },
{ DHGServer.newFactory(BuiltinDHFactories.dhg14_256), DHGroups.Group14SHA256() },
{ DHGServer.newFactory(BuiltinDHFactories.dhg15_512), DHGroups.Group15SHA512() },
{ DHGServer.newFactory(BuiltinDHFactories.dhg16_512), DHGroups.Group16SHA512() },
{ DHGServer.newFactory(BuiltinDHFactories.dhg17_512), DHGroups.Group17SHA512() },
{ DHGServer.newFactory(BuiltinDHFactories.dhg18_512), DHGroups.Group18SHA512() },
});
}
private final Factory.Named<net.schmizz.sshj.transport.kex.KeyExchange> clientFactory;
private final KeyExchangeFactory serverFactory;
@TestFactory
public Stream<DynamicTest> keyExchangeTests() {
return getParameters().stream().map(params -> {
KeyExchangeFactory serverFactory = (KeyExchangeFactory) params[0];
Factory.Named<net.schmizz.sshj.transport.kex.KeyExchange> clientFactory = (Factory.Named<net.schmizz.sshj.transport.kex.KeyExchange>) params[1];
SingletonRandomFactory randomFactory = new SingletonRandomFactory(new JCERandom.Factory());
public KeyExchangeTest(KeyExchangeFactory serverFactory, Factory.Named<net.schmizz.sshj.transport.kex.KeyExchange> clientFactory) {
this.clientFactory = clientFactory;
this.serverFactory = serverFactory;
}
return DynamicTest.dynamicTest(serverFactory.getName() + " <-> " + clientFactory.getName(), () -> {
try (SshServerExtension fixture = new SshServerExtension(false)) {
for (int i = 0; i < 10; i++) {
logger.info("--> Attempt {}", i);
fixture.getServer().setKeyExchangeFactories(Collections.singletonList(serverFactory));
fixture.start();
Config config = new DefaultConfig();
config.setRandomFactory(randomFactory);
config.setKeyExchangeFactories(Collections.singletonList(clientFactory));
@Override
protected Config getClientConfig(DefaultConfig config) {
config.setKeyExchangeFactories(Collections.singletonList(clientFactory));
return config;
}
@Override
protected void configureServer(SshServer server) {
server.setKeyExchangeFactories(Collections.singletonList(serverFactory));
SSHClient sshClient = fixture.connectClient(fixture.setupClient(config));
assertThat("should be connected", sshClient.isConnected());
sshClient.disconnect();
fixture.stopClient();
};
};
});
});
}
}

View File

@@ -15,24 +15,24 @@
*/
package com.hierynomus.sshj.userauth;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.userauth.method.AuthGssApiWithMic;
import net.schmizz.sshj.util.gss.BogusGSSManager;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import javax.security.auth.login.AppConfigurationEntry;
import javax.security.auth.login.Configuration;
import javax.security.auth.login.LoginContext;
import java.util.Collections;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class GssApiTest {
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
private static final String LOGIN_CONTEXT_NAME = "TestLoginContext";

View File

@@ -14,11 +14,11 @@
package com.hierynomus.sshj.userauth.keyprovider.bcrypt;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* JUnit unit tests for BCrypt routines

View File

@@ -15,16 +15,16 @@
*/
package com.hierynomus.sshj.userauth.method;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.userauth.method.AuthKeyboardInteractive;
import net.schmizz.sshj.userauth.method.ChallengeResponseProvider;
import net.schmizz.sshj.userauth.password.Resource;
import org.apache.sshd.server.auth.keyboard.UserAuthKeyboardInteractiveFactory;
import org.apache.sshd.server.auth.password.AcceptAllPasswordAuthenticator;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.IOException;
import java.util.ArrayList;
@@ -34,10 +34,10 @@ import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
public class AuthKeyboardInteractiveTest {
@Rule
public SshFixture fixture = new SshFixture(false);
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension(false);
@Before
@BeforeEach
public void setKeyboardInteractiveAuthenticator() throws IOException {
fixture.getServer().setUserAuthFactories(Collections.singletonList(new UserAuthKeyboardInteractiveFactory()));
fixture.getServer().setPasswordAuthenticator(AcceptAllPasswordAuthenticator.INSTANCE);

View File

@@ -15,7 +15,7 @@
*/
package com.hierynomus.sshj.userauth.method;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.userauth.UserAuthException;
import net.schmizz.sshj.userauth.password.PasswordFinder;
@@ -25,23 +25,23 @@ import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.auth.password.PasswordChangeRequiredException;
import org.apache.sshd.server.auth.password.UserAuthPasswordFactory;
import org.apache.sshd.server.session.ServerSession;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.IOException;
import java.util.Collections;
import java.util.Stack;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class AuthPasswordTest {
@Rule
public SshFixture fixture = new SshFixture(false);
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension(false);
@Before
@BeforeEach
public void setPasswordAuthenticator() throws IOException {
fixture.getServer().setUserAuthFactories(Collections.singletonList(new UserAuthPasswordFactory()));
fixture.getServer().setPasswordAuthenticator(new PasswordAuthenticator() {

View File

@@ -19,13 +19,13 @@ import net.schmizz.sshj.userauth.method.PasswordResponseProvider;
import net.schmizz.sshj.userauth.password.AccountResource;
import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.Resource;
import org.jetbrains.annotations.NotNull;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.*;
public class PasswordResponseProviderTest {
private static final char[] PASSWORD = "the_password".toCharArray();
private static final AccountResource ACCOUNT_RESOURCE = new AccountResource("user", "host");
@@ -64,13 +64,13 @@ public class PasswordResponseProviderTest {
@Test
public void shouldPassRetry() {
Assert.assertFalse(createDefaultResponseProvider(false).shouldRetry());
Assert.assertTrue(createDefaultResponseProvider(true).shouldRetry());
assertFalse(createDefaultResponseProvider(false).shouldRetry());
assertTrue(createDefaultResponseProvider(true).shouldRetry());
}
@Test
public void shouldHaveNoSubmethods() {
Assert.assertEquals(createDefaultResponseProvider(true).getSubmethods(), Collections.emptyList());
assertEquals(createDefaultResponseProvider(true).getSubmethods(), Collections.emptyList());
}
@Test
@@ -91,10 +91,9 @@ public class PasswordResponseProviderTest {
}
private static void checkPrompt(PasswordResponseProvider responseProvider, String prompt, char[] expected) {
Assert.assertArrayEquals("Prompt '" + prompt + "'", expected, responseProvider.getResponse(prompt, false));
assertArrayEquals(expected, responseProvider.getResponse(prompt, false), "Prompt '" + prompt + "'");
}
@NotNull
private static PasswordResponseProvider createDefaultResponseProvider(final boolean shouldRetry) {
PasswordFinder passwordFinder = new TestPasswordFinder(shouldRetry);
PasswordResponseProvider responseProvider = new PasswordResponseProvider(passwordFinder);
@@ -111,13 +110,13 @@ public class PasswordResponseProviderTest {
@Override
public char[] reqPassword(Resource<?> resource) {
Assert.assertEquals(resource, ACCOUNT_RESOURCE);
assertEquals(resource, ACCOUNT_RESOURCE);
return PASSWORD;
}
@Override
public boolean shouldRetry(Resource<?> resource) {
Assert.assertEquals(resource, ACCOUNT_RESOURCE);
assertEquals(resource, ACCOUNT_RESOURCE);
return shouldRetry;
}
}

View File

@@ -15,21 +15,20 @@
*/
package net.schmizz.sshj;
import com.hierynomus.sshj.test.SshFixture;
import org.junit.Test;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.channel.direct.Session;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.fail;
public class LoadsOfConnects {
protected final Logger log = LoggerFactory.getLogger(getClass());
private final SshFixture fixture = new SshFixture();
private final SshServerExtension fixture = new SshServerExtension();
@Test
public void loadsOfConnects() {
@@ -40,7 +39,7 @@ public class LoadsOfConnects {
SSHClient client = fixture.setupConnectedDefaultClient();
client.authPassword("test", "test");
Session s = client.startSession();
Session.Command c = s.exec(SshFixture.listCommand);
Session.Command c = s.exec(SshServerExtension.listCommand);
IOUtils.readFully(c.getErrorStream());
IOUtils.readFully(c.getInputStream());
c.close();

View File

@@ -15,30 +15,30 @@
*/
package net.schmizz.sshj;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.userauth.UserAuthException;
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 java.io.IOException;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
/* Kinda basic right now */
public class SmokeTest {
private final SshFixture fixture = new SshFixture();
private final SshServerExtension fixture = new SshServerExtension();
@Before
@BeforeEach
public void setUp()
throws IOException {
fixture.start();
fixture.setupConnectedDefaultClient();
}
@After
@AfterEach
public void tearDown()
throws IOException, InterruptedException {
fixture.stopClient();
@@ -58,4 +58,4 @@ public class SmokeTest {
assertTrue(fixture.getClient().isAuthenticated());
}
}
}

View File

@@ -17,11 +17,11 @@ package net.schmizz.sshj.common;
import net.schmizz.sshj.common.Buffer.BufferException;
import net.schmizz.sshj.common.Buffer.PlainBuffer;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
public class BufferTest {
@@ -162,7 +162,7 @@ public class BufferTest {
for (long value : values) {
byte[] bytesBigInt = new PlainBuffer().putUInt64(BigInteger.valueOf(value)).getCompactData();
byte[] bytesLong = new PlainBuffer().putUInt64(value).getCompactData();
assertArrayEquals("Value: " + value, bytesLong, bytesBigInt);
assertArrayEquals(bytesLong, bytesBigInt, "Value: " + value);
}
}

View File

@@ -15,13 +15,13 @@
*/
package net.schmizz.sshj.common;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.Random;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;

View File

@@ -18,7 +18,7 @@ package net.schmizz.sshj.connection.channel;
import net.schmizz.concurrent.Event;
import net.schmizz.concurrent.ExceptionChainer;
import net.schmizz.sshj.common.LoggerFactory;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.Socket;
@@ -86,4 +86,4 @@ public class SocketStreamCopyMonitorTest {
}
}, LoggerFactory.DEFAULT);
}
}
}

View File

@@ -15,12 +15,12 @@
*/
package net.schmizz.sshj.connection.channel.direct;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
public class ParametersTest {

View File

@@ -17,12 +17,12 @@ package net.schmizz.sshj.keyprovider;
import net.schmizz.sshj.userauth.keyprovider.KeyFormat;
import net.schmizz.sshj.userauth.keyprovider.KeyProviderUtil;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class KeyProviderUtilTest {

View File

@@ -26,20 +26,11 @@ import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.PasswordUtils;
import net.schmizz.sshj.userauth.password.Resource;
import net.schmizz.sshj.util.KeyUtil;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.*;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
@@ -54,7 +45,7 @@ import java.util.*;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
public class OpenSSHKeyFileTest {
@@ -141,8 +132,8 @@ public class OpenSSHKeyFileTest {
}
};
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@TempDir
public File temporaryFolder;
@Test
public void blankingOut()
@@ -254,8 +245,9 @@ public class OpenSSHKeyFileTest {
checkOpenSSHKeyV1("src/test/resources/keytypes/ed25519_aes128cbc.pem", "sshjtest", true);
}
@Test(expected = KeyDecryptionFailedException.class)
@Test
public void shouldFailOnIncorrectPassphraseAfterRetries() throws IOException {
assertThrows(KeyDecryptionFailedException.class, () -> {
OpenSSHKeyV1KeyFile keyFile = new OpenSSHKeyV1KeyFile();
keyFile.init(new File("src/test/resources/keytypes/ed25519_aes256cbc.pem"), new PasswordFinder() {
private int reqCounter = 0;
@@ -272,6 +264,8 @@ public class OpenSSHKeyFileTest {
}
});
keyFile.getPrivate();
});
}
@Test
@@ -295,20 +289,20 @@ public class OpenSSHKeyFileTest {
assertTrue(privateKey instanceof RSAPrivateCrtKey);
final RSAPrivateCrtKey rsaPrivateCrtKey = (RSAPrivateCrtKey) privateKey;
assertEquals("Public Key Exponent not matched", rsaPublicKey.getPublicExponent(), rsaPrivateCrtKey.getPublicExponent());
assertEquals("Public Key Modulus not matched", rsaPublicKey.getModulus(), rsaPrivateCrtKey.getModulus());
assertEquals(rsaPublicKey.getPublicExponent(), rsaPrivateCrtKey.getPublicExponent(), "Public Key Exponent not matched");
assertEquals(rsaPublicKey.getModulus(), rsaPrivateCrtKey.getModulus(), "Public Key Modulus not matched");
final BigInteger privateExponent = rsaPrivateCrtKey.getPrivateExponent();
final BigInteger expectedPrimeExponentP = privateExponent.mod(rsaPrivateCrtKey.getPrimeP().subtract(BigInteger.ONE));
assertEquals("Prime Exponent P not matched", expectedPrimeExponentP, rsaPrivateCrtKey.getPrimeExponentP());
assertEquals(expectedPrimeExponentP, rsaPrivateCrtKey.getPrimeExponentP(), "Prime Exponent P not matched");
final BigInteger expectedPrimeExponentQ = privateExponent.mod(rsaPrivateCrtKey.getPrimeQ().subtract(BigInteger.ONE));
assertEquals("Prime Exponent Q not matched", expectedPrimeExponentQ, rsaPrivateCrtKey.getPrimeExponentQ());
assertEquals(expectedPrimeExponentQ, rsaPrivateCrtKey.getPrimeExponentQ(), "Prime Exponent Q not matched");
final BigInteger expectedCoefficient = rsaPrivateCrtKey.getPrimeQ().modInverse(rsaPrivateCrtKey.getPrimeP());
assertEquals("Prime CRT Coefficient not matched", expectedCoefficient, rsaPrivateCrtKey.getCrtCoefficient());
assertEquals(expectedCoefficient, rsaPrivateCrtKey.getCrtCoefficient(), "Prime CRT Coefficient not matched");
}
@Test
@@ -411,7 +405,9 @@ public class OpenSSHKeyFileTest {
public void notTrimmedKeys() throws IOException {
File initialPrivateKey = new File("src/test/resources/id_rsa");
File initialPublicKey = new File("src/test/resources/id_rsa.pub");
File corruptedPrivateKey = new File(temporaryFolder.newFolder(), "id_rsa");
File folder = new File(temporaryFolder, "keys");
assertTrue(folder.mkdir());
File corruptedPrivateKey = new File(folder, "id_rsa");
File corruptedPublicKey = new File(corruptedPrivateKey.getParent(), "id_rsa.pub");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(initialPrivateKey)));
@@ -449,10 +445,10 @@ public class OpenSSHKeyFileTest {
FileKeyProvider keyProvider = new OpenSSHKeyV1KeyFile();
keyProvider.init(new StringReader(""));
assertThrows("This key is not in 'openssh-key-v1' format", IOException.class, keyProvider::getPrivate);
assertThrows(IOException.class, keyProvider::getPrivate, "This key is not in 'openssh-key-v1' format");
}
@Before
@BeforeEach
public void checkBCRegistration() {
if (!SecurityUtils.isBouncyCastleRegistered()) {
throw new AssertionError("bouncy castle needed");

View File

@@ -23,15 +23,15 @@ import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.PasswordUtils;
import net.schmizz.sshj.userauth.password.Resource;
import net.schmizz.sshj.util.KeyUtil;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PKCS8KeyFileTest {

View File

@@ -19,7 +19,7 @@ import com.hierynomus.sshj.userauth.keyprovider.OpenSSHKeyV1KeyFile;
import net.schmizz.sshj.userauth.keyprovider.PKCS8KeyFile;
import net.schmizz.sshj.userauth.keyprovider.PuTTYKeyFile;
import net.schmizz.sshj.util.UnitTestPasswordFinder;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -27,9 +27,7 @@ import java.io.StringReader;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.*;
public class PuTTYKeyFileTest {
@@ -530,13 +528,15 @@ public class PuTTYKeyFileTest {
assertNotNull(key.getPublic());
}
@Test(expected = IOException.class)
@Test
public void testWrongPassphraseRsa() throws Exception {
PuTTYKeyFile key = new PuTTYKeyFile();
key.init(new StringReader(ppk1024_passphrase),
new UnitTestPasswordFinder("egfsdgdfgsdfsdfasfs523534dgdsgdfa"));
assertNotNull(key.getPublic());
assertNull(key.getPrivate());
assertThrows(IOException.class, () -> {
PuTTYKeyFile key = new PuTTYKeyFile();
key.init(new StringReader(ppk1024_passphrase),
new UnitTestPasswordFinder("egfsdgdfgsdfsdfasfs523534dgdsgdfa"));
assertNotNull(key.getPublic());
assertNull(key.getPrivate());
});
}
@Test
@@ -548,12 +548,14 @@ public class PuTTYKeyFileTest {
assertNotNull(key.getPublic());
}
@Test(expected = IOException.class)
@Test
public void testWrongPassphraseDsa() throws Exception {
PuTTYKeyFile key = new PuTTYKeyFile();
key.init(new StringReader(ppkdsa_passphrase),
new UnitTestPasswordFinder("egfsdgdfgsdfsdfasfs523534dgdsgdfa"));
assertNotNull(key.getPublic());
assertNull(key.getPrivate());
assertThrows(IOException.class, () -> {
PuTTYKeyFile key = new PuTTYKeyFile();
key.init(new StringReader(ppkdsa_passphrase),
new UnitTestPasswordFinder("egfsdgdfgsdfsdfasfs523534dgdsgdfa"));
assertNotNull(key.getPublic());
assertNull(key.getPrivate());
});
}
}

View File

@@ -15,10 +15,10 @@
*/
package net.schmizz.sshj.sftp;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
public class FileModeTest {

View File

@@ -18,8 +18,8 @@ package net.schmizz.sshj.sftp;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.connection.channel.direct.Session.Subsystem;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.DataOutputStream;
@@ -27,14 +27,14 @@ import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Arrays;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
public class PacketReaderTest {
private DataOutputStream dataout;
private PacketReader reader;
@Before
@BeforeEach
public void setUp() throws Exception {
PipedOutputStream pipedout = new PipedOutputStream();
PipedInputStream pipedin = new PipedInputStream(pipedout);
@@ -59,7 +59,7 @@ public class PacketReaderTest {
SFTPPacket<Response> packet = reader.readPacket();
assertEquals(packet.available(), 10);
assertTrue("actual=" + Arrays.toString(packet.array()), Arrays.equals(bytes, subArray(packet.array(), 0, 10)));
assertTrue(Arrays.equals(bytes, subArray(packet.array(), 0, 10)), "actual=" + Arrays.toString(packet.array()));
}
@Test

View File

@@ -16,8 +16,8 @@
package net.schmizz.sshj.sftp;
import net.schmizz.sshj.common.LoggerFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -27,7 +27,7 @@ import static org.mockito.Mockito.*;
public class SFTPClientTest {
private final SFTPEngine sftpEngine = mock(SFTPEngine.class);
@Before
@BeforeEach
public void setPathHelper() throws Exception {
PathHelper helper = new PathHelper(new PathHelper.Canonicalizer() {
/**
@@ -48,7 +48,7 @@ public class SFTPClientTest {
when(sftpEngine.getLoggerFactory()).thenReturn(LoggerFactory.DEFAULT);
}
@Before
@BeforeEach
public void setRemoteWorkingDirectory() throws IOException {
FileAttributes isADirectory = new FileAttributes.Builder().withType(FileMode.Type.DIRECTORY).build();
when(sftpEngine.stat("/workingdirectory")).thenReturn(isADirectory);

View File

@@ -15,71 +15,74 @@
*/
package net.schmizz.sshj.sftp;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import com.hierynomus.sshj.test.util.FileUtil;
import java.io.File;
import java.io.IOException;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.StreamCopier;
import net.schmizz.sshj.xfer.TransferListener;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SFTPFileTransferTest {
public static final String TARGET_FILE_NAME = "target.txt";
File targetDir;
File targetFile;
File sourceFile;
File partialFile;
SSHClient sshClient;
SFTPFileTransfer xfer;
ByteCounter listener;
@Rule
public SshFixture fixture = new SshFixture();
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Before
@TempDir
public File tempFolder;
@BeforeEach
public void init() throws IOException {
targetDir = tempFolder.newFolder();
targetDir = new File(tempFolder, "targetDir");
assertTrue(targetDir.mkdir());
targetFile = new File(targetDir, TARGET_FILE_NAME);
sourceFile = new File("src/test/resources/files/test_file_full.txt");
partialFile = new File("src/test/resources/files/test_file_partial.txt");
sshClient = fixture.setupConnectedDefaultClient();
sshClient.authPassword("test", "test");
xfer = sshClient.newSFTPClient().getFileTransfer();
xfer.setTransferListener(listener = new ByteCounter());
}
@After
@AfterEach
public void cleanup() {
if (targetFile.exists()) {
targetFile.delete();
}
if (targetDir.exists()) {
targetDir.delete();
}
}
private void performDownload(long byteOffset) throws IOException {
assertTrue(listener.getBytesTransferred() == 0);
long expectedBytes = 0;
// Using the resume param this way to call the different entry points into the FileTransfer interface
if (byteOffset > 0) {
expectedBytes = sourceFile.length() - targetFile.length(); // only the difference between what is there and what should be
@@ -88,16 +91,16 @@ public class SFTPFileTransferTest {
expectedBytes = sourceFile.length(); // the entire source file should be transferred
xfer.download(sourceFile.getAbsolutePath(), targetFile.getAbsolutePath());
}
assertTrue(FileUtil.compareFileContents(sourceFile, targetFile));
assertTrue(listener.getBytesTransferred() == expectedBytes);
}
private void performUpload(long byteOffset) throws IOException {
assertTrue(listener.getBytesTransferred() == 0);
long expectedBytes = 0;
// Using the resume param this way to call the different entry points into the FileTransfer interface
if (byteOffset > 0) {
expectedBytes = sourceFile.length() - targetFile.length(); // only the difference between what is there and what should be
@@ -109,64 +112,64 @@ public class SFTPFileTransferTest {
assertTrue(FileUtil.compareFileContents(sourceFile, targetFile));
assertTrue(listener.getBytesTransferred() == expectedBytes);
}
@Test
public void testDownload() throws IOException {
performDownload(0);
}
@Test
public void testDownloadResumePartial() throws IOException {
FileUtil.writeToFile(targetFile, FileUtil.readFromFile(partialFile));
assertFalse(FileUtil.compareFileContents(sourceFile, targetFile));
performDownload(targetFile.length());
}
@Test
public void testDownloadResumeNothing() throws IOException {
assertFalse(targetFile.exists());
performDownload(targetFile.length());
}
@Test
public void testDownloadResumePreviouslyCompleted() throws IOException {
FileUtil.writeToFile(targetFile, FileUtil.readFromFile(sourceFile));
assertTrue(FileUtil.compareFileContents(sourceFile, targetFile));
performDownload(targetFile.length());
}
@Test
public void testUpload() throws IOException {
performUpload(0);
}
@Test
public void testUploadResumePartial() throws IOException {
FileUtil.writeToFile(targetFile, FileUtil.readFromFile(partialFile));
assertFalse(FileUtil.compareFileContents(sourceFile, targetFile));
performUpload(targetFile.length());
}
@Test
public void testUploadResumeNothing() throws IOException {
assertFalse(targetFile.exists());
performUpload(targetFile.length());
}
@Test
public void testUploadResumePreviouslyCompleted() throws IOException {
FileUtil.writeToFile(targetFile, FileUtil.readFromFile(sourceFile));
assertTrue(FileUtil.compareFileContents(sourceFile, targetFile));
performUpload(targetFile.length());
}
public class ByteCounter implements TransferListener, StreamCopier.Listener {
long bytesTransferred;
public long getBytesTransferred() {
return bytesTransferred;
}
@Override
public TransferListener directory(String name) {
return this;

View File

@@ -15,6 +15,12 @@
*/
package net.schmizz.sshj.signature;
import com.hierynomus.sshj.common.KeyAlgorithm;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.IOUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
@@ -22,19 +28,13 @@ import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.util.Arrays;
import com.hierynomus.sshj.common.KeyAlgorithm;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.IOUtils;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SignatureDSATest {
private KeyFactory keyFactory;
@Before
@BeforeEach
public void setUp() throws NoSuchAlgorithmException {
keyFactory = KeyFactory.getInstance(KeyAlgorithm.DSA);
}
@@ -61,9 +61,9 @@ public class SignatureDSATest {
SignatureDSA signatureForVerifying = new SignatureDSA();
signatureForVerifying.initVerify(keyFactory.generatePublic(new DSAPublicKeySpec(y, p, q, g)));
signatureForVerifying.update(data);
Assert.assertTrue("Failed to verify signature: " + Arrays.toString(sigFull), signatureForVerifying.verify(sigFull));
assertTrue(signatureForVerifying.verify(sigFull), "Failed to verify signature: " + Arrays.toString(sigFull));
signatureForVerifying.update(data);
Assert.assertTrue("Failed to verify signature: " + Arrays.toString(dataSig), signatureForVerifying.verify(dataSig));
assertTrue(signatureForVerifying.verify(dataSig), "Failed to verify signature: " + Arrays.toString(dataSig));
}
}

View File

@@ -17,11 +17,12 @@ package net.schmizz.sshj.signature;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.Buffer.BufferException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.security.PublicKey;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SignatureECDSATest {
@Test
@@ -35,10 +36,10 @@ public class SignatureECDSATest {
Signature signature = new SignatureECDSA.Factory256().create();
signature.initVerify(hostKey);
signature.update(H, 0, H.length);
Assert.assertTrue("ECDSA256 signature verifies", signature.verify(sig));
assertTrue(signature.verify(sig), "ECDSA256 signature verifies");
}
@Test
public void testECDSA384Verifies() throws BufferException {
byte[] K_S = fromString("0, 0, 0, 19, 101, 99, 100, 115, 97, 45, 115, 104, 97, 50, 45, 110, 105, 115, 116, 112, 51, 56, 52, 0, 0, 0, 8, 110, 105, 115, 116, 112, 51, 56, 52, 0, 0, 0, 97, 4, 105, 52, -67, 89, 21, 53, -125, -26, -23, -125, 48, 119, -63, -66, 30, -46, -110, 21, 14, -96, -28, 40, -108, 60, 120, 110, 58, 30, -56, 37, 6, -17, -25, 109, 84, 67, -19, 0, -30, -33, 54, 94, -121, 49, 68, -66, 14, 6, 76, -51, 102, -123, 59, -24, -34, 79, -51, 64, -48, -45, 21, -42, -96, -123, -27, -21, 15, 56, -96, -12, 73, -10, 113, -20, -22, 38, 100, 38, -85, -113, 46, 36, 17, -30, 89, 40, 16, 104, 123, 50, 8, 122, 49, -41, -97, 95");
@@ -50,10 +51,10 @@ public class SignatureECDSATest {
Signature signature = new SignatureECDSA.Factory384().create();
signature.initVerify(hostKey);
signature.update(H, 0, H.length);
Assert.assertTrue("ECDSA384 signature verifies", signature.verify(sig));
assertTrue(signature.verify(sig), "ECDSA384 signature verifies");
}
@Test
public void testECDSA521Verifies() throws BufferException {
byte[] K_S = fromString("0, 0, 0, 19, 101, 99, 100, 115, 97, 45, 115, 104, 97, 50, 45, 110, 105, 115, 116, 112, 53, 50, 49, 0, 0, 0, 8, 110, 105, 115, 116, 112, 53, 50, 49, 0, 0, 0, -123, 4, 1, -56, 55, 64, -73, -109, 95, 94, -107, -116, -46, -16, 119, -66, -68, 41, -103, -66, 102, -123, -69, 59, -8, 106, 72, 75, 7, 56, -79, 109, -88, 77, 12, -97, -109, -32, -60, 64, -75, -48, 50, -51, -68, -81, 75, 110, -7, -79, -32, -36, -73, -7, -65, -24, 40, -74, 58, 43, -26, -5, -55, 125, -32, -89, -54, -111, 0, 81, 37, -73, 60, 69, 107, -108, 115, 60, -61, 22, 6, -128, -69, -28, 122, -26, -37, -117, 121, -106, -126, 23, -90, 127, 73, -58, -113, -61, 105, 68, 116, 85, -115, -47, 90, 122, 109, -21, 127, 39, -75, -58, -109, 73, -82, -122, -11, -44, -87, 85, -100, -4, -123, -31, 126, -94, 127, 96, 9, -30, 70, -113, -42, 28");
@@ -65,17 +66,17 @@ public class SignatureECDSATest {
Signature signature = new SignatureECDSA.Factory521().create();
signature.initVerify(hostKey);
signature.update(H, 0, H.length);
Assert.assertTrue("ECDSA521 signature verifies", signature.verify(sig));
assertTrue(signature.verify(sig), "ECDSA521 signature verifies");
}
private byte[] fromString(String string) {
String[] split = string.split(", ");
byte[] res = new byte[split.length];
for (int i = 0; i < split.length; i++)
res[i] = Byte.parseByte(split[i]);
return res;
}
}

View File

@@ -16,11 +16,12 @@
package net.schmizz.sshj.signature;
import net.schmizz.sshj.common.Buffer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.security.PublicKey;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SignatureRSATest {
@@ -36,7 +37,7 @@ public class SignatureRSATest {
signature.initVerify(hostKey);
signature.update(msg, 0, msg.length);
Assert.assertTrue("RSACERT signature verifies", signature.verify(sig));
assertTrue(signature.verify(sig), "RSACERT signature verifies");
}
private byte[] fromString(String string) {

View File

@@ -23,13 +23,13 @@ import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.transport.cipher.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.security.SecureRandom;
import java.security.Security;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@@ -47,7 +47,7 @@ public class DecoderDecryptGcmCipherSshPacketTest {
private Decoder decoder;
@Before
@BeforeEach
public void setUp() throws Exception {
Security.addProvider(new BouncyCastleProvider());
ClassLoader classLoader = DecoderDecryptGcmCipherSshPacketTest.class.getClassLoader();

View File

@@ -16,13 +16,13 @@
package net.schmizz.sshj.transport.kex;
import net.schmizz.sshj.transport.random.JCERandom;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public class Curve25519DHTest {

View File

@@ -15,17 +15,17 @@
*/
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import net.schmizz.sshj.common.SSHRuntimeException;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import com.hierynomus.sshj.transport.mac.Macs;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
public class BaseMacTest {
private static final Charset CHARSET = Charset.forName("US-ASCII");
@@ -41,11 +41,13 @@ public class BaseMacTest {
assertThat(Hex.toHexString(hmac.doFinal()), is(EXPECTED_HMAC));
}
@Test(expected = SSHRuntimeException.class)
@Test
public void testUnknownAlgorithm() {
BaseMAC hmac = new BaseMAC("AlgorithmThatDoesNotExist", 20, 20, false);
hmac.init((KEY + "foo").getBytes(CHARSET));
fail("Should not initialize a non-existent MAC");
assertThrows(SSHRuntimeException.class, () -> {
BaseMAC hmac = new BaseMAC("AlgorithmThatDoesNotExist", 20, 20, false);
hmac.init((KEY + "foo").getBytes(CHARSET));
fail("Should not initialize a non-existent MAC");
});
}
@Test

View File

@@ -15,15 +15,14 @@
*/
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import com.hierynomus.sshj.transport.mac.Macs;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACMD596Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");

View File

@@ -15,15 +15,14 @@
*/
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import com.hierynomus.sshj.transport.mac.Macs;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACMD5Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");

View File

@@ -15,15 +15,14 @@
*/
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import com.hierynomus.sshj.transport.mac.Macs;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA196Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");

View File

@@ -15,15 +15,14 @@
*/
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import com.hierynomus.sshj.transport.mac.Macs;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA1Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");

View File

@@ -15,15 +15,14 @@
*/
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import com.hierynomus.sshj.transport.mac.Macs;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA2256Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");

View File

@@ -15,15 +15,14 @@
*/
package net.schmizz.sshj.transport.mac;
import com.hierynomus.sshj.transport.mac.Macs;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import java.nio.charset.Charset;
import com.hierynomus.sshj.transport.mac.Macs;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
public class HMACSHA2512Test {
private static final Charset CHARSET = Charset.forName("US-ASCII");

View File

@@ -15,12 +15,13 @@
*/
package net.schmizz.sshj.userauth.password;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.Console;
import static org.junit.jupiter.api.Assertions.*;
public class TestConsolePasswordFinder {
private static final String FORMAT = "%s";
@@ -36,8 +37,7 @@ public class TestConsolePasswordFinder {
Resource resource = Mockito.mock(Resource.class);
char[] password = new ConsolePasswordFinder(console).reqPassword(resource);
Assert.assertArrayEquals("Password should match mocked return value",
expectedPassword, password);
assertArrayEquals(expectedPassword, password, "Password should match mocked return value");
Mockito.verifyNoMoreInteractions(resource);
}
@@ -46,7 +46,7 @@ public class TestConsolePasswordFinder {
Resource<?> resource = Mockito.mock(Resource.class);
char[] password = new ConsolePasswordFinder(null, FORMAT, 1).reqPassword(resource);
Assert.assertNull("Password should be null with null console", password);
assertNull(password, "Password should be null with null console");
Mockito.verifyNoMoreInteractions(resource);
}
@@ -54,30 +54,28 @@ public class TestConsolePasswordFinder {
public void testShouldRetry() {
Resource<String> resource = new PrivateKeyStringResource("");
ConsolePasswordFinder finder = new ConsolePasswordFinder(null, FORMAT, 1);
Assert.assertTrue("Should allow a retry at first", finder.shouldRetry(resource));
assertTrue(finder.shouldRetry(resource), "Should allow a retry at first");
finder.reqPassword(resource);
Assert.assertFalse("Should stop allowing retries after one interaction", finder.shouldRetry(resource));
assertFalse(finder.shouldRetry(resource), "Should stop allowing retries after one interaction");
}
@Test
public void testPromptFormat() {
Assert.assertNotNull(
"Empty format should create valid ConsolePasswordFinder",
new ConsolePasswordFinder(null, "", 1));
Assert.assertNotNull(
"Single-string format should create valid ConsolePasswordFinder",
new ConsolePasswordFinder(null, FORMAT, 1));
assertNotNull(
new ConsolePasswordFinder(null, "", 1), "Empty format should create valid ConsolePasswordFinder");
assertNotNull(
new ConsolePasswordFinder(null, FORMAT, 1), "Single-string format should create valid ConsolePasswordFinder");
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testPromptFormatTooManyMarkers() {
new ConsolePasswordFinder(null, "%s%s", 1);
assertThrows(IllegalArgumentException.class, () -> new ConsolePasswordFinder(null, "%s%s", 1));
}
@Test(expected = IllegalArgumentException.class)
@Test
public void testPromptFormatWrongMarkerType() {
new ConsolePasswordFinder(null, "%d", 1);
assertThrows(IllegalArgumentException.class, () -> new ConsolePasswordFinder(null, "%d", 1));
}
}

View File

@@ -32,15 +32,14 @@ package net.schmizz.sshj.util;
import net.schmizz.sshj.common.Buffer;
import net.schmizz.sshj.common.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.*;
/** Tests {@link Buffer} functionality */
public class BufferTest {
@@ -48,7 +47,7 @@ public class BufferTest {
private Buffer.PlainBuffer posBuf;
private Buffer.PlainBuffer handyBuf;
@Before
@BeforeEach
public void setUp()
throws UnsupportedEncodingException, GeneralSecurityException {
// for position test
@@ -113,14 +112,15 @@ public class BufferTest {
// TODO stub
}
@Test(expected = Buffer.BufferException.class)
public void testUnderflow()
throws Buffer.BufferException {
// exhaust the buffer
for (int i = 0; i < 5; ++i)
@Test
public void testUnderflow() throws Buffer.BufferException {
assertThrows(Buffer.BufferException.class, () -> {
// exhaust the buffer
for (int i = 0; i < 5; ++i)
posBuf.readByte();
// underflow
posBuf.readByte();
// underflow
posBuf.readByte();
});
}
}

View File

@@ -15,97 +15,103 @@
*/
package net.schmizz.sshj.xfer.scp;
import com.hierynomus.sshj.test.SshFixture;
import com.hierynomus.sshj.test.SshServerExtension;
import com.hierynomus.sshj.test.util.FileUtil;
import net.schmizz.sshj.SSHClient;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SCPFileTransferTest {
public static final String DEFAULT_FILE_NAME = "my_file.txt";
File targetDir;
File sourceFile;
File targetFile;
Path targetDir;
Path sourceFile;
Path targetFile;
SSHClient sshClient;
@Rule
public SshFixture fixture = new SshFixture();
@RegisterExtension
public SshServerExtension fixture = new SshServerExtension();
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@TempDir
public File tempFolder;
@Before
@BeforeEach
public void init() throws IOException {
sourceFile = tempFolder.newFile(DEFAULT_FILE_NAME);
FileUtil.writeToFile(sourceFile, "This is my file");
targetDir = tempFolder.newFolder();
targetFile = new File(targetDir, DEFAULT_FILE_NAME);
sourceFile = Files.createFile(tempFolder.toPath().resolve(DEFAULT_FILE_NAME));
FileUtil.writeToFile(sourceFile.toFile(), "This is my file");
targetDir = Files.createDirectory(tempFolder.toPath().resolve("folder"));
targetFile = targetDir.resolve(DEFAULT_FILE_NAME);
sshClient = fixture.setupConnectedDefaultClient();
sshClient.authPassword("test", "test");
}
@After
@AfterEach
public void cleanup() {
if (targetFile.exists()) {
targetFile.delete();
if (Files.exists(targetFile)) {
try {
Files.delete(targetFile);
} catch (IOException ioe) {
// ok
}
}
}
@Test
public void shouldSCPUploadFile() throws IOException {
SCPFileTransfer scpFileTransfer = sshClient.newSCPFileTransfer();
assertFalse(targetFile.exists());
assertTrue(targetDir.exists());
scpFileTransfer.upload(sourceFile.getAbsolutePath(), targetDir.getAbsolutePath());
assertTrue(targetFile.exists());
assertFalse(Files.exists(targetFile));
assertTrue(Files.exists(targetDir));
scpFileTransfer.upload(sourceFile.toAbsolutePath().toString(), targetDir.toAbsolutePath().toString());
assertTrue(Files.exists(targetFile));
}
@Test
public void shouldSCPUploadFileWithBandwidthLimit() throws IOException {
// Limit upload transfer at 2Mo/s
SCPFileTransfer scpFileTransfer = sshClient.newSCPFileTransfer().bandwidthLimit(16000);
assertFalse(targetFile.exists());
scpFileTransfer.upload(sourceFile.getAbsolutePath(), targetDir.getAbsolutePath());
assertTrue(targetFile.exists());
assertFalse(Files.exists(targetFile));
scpFileTransfer.upload(sourceFile.toAbsolutePath().toString(), targetDir.toAbsolutePath().toString());
assertTrue(Files.exists(targetFile));
}
@Test
public void shouldSCPDownloadFile() throws IOException {
SCPFileTransfer scpFileTransfer = sshClient.newSCPFileTransfer();
assertFalse(targetFile.exists());
scpFileTransfer.download(sourceFile.getAbsolutePath(), targetDir.getAbsolutePath());
assertTrue(targetFile.exists());
assertFalse(Files.exists(targetFile));
scpFileTransfer.download(sourceFile.toAbsolutePath().toString(), targetDir.toAbsolutePath().toString());
assertTrue(Files.exists(targetFile));
}
@Test
public void shouldSCPDownloadFileWithBandwidthLimit() throws IOException {
// Limit download transfer at 128Ko/s
SCPFileTransfer scpFileTransfer = sshClient.newSCPFileTransfer().bandwidthLimit(1024);
assertFalse(targetFile.exists());
scpFileTransfer.download(sourceFile.getAbsolutePath(), targetDir.getAbsolutePath());
assertTrue(targetFile.exists());
assertFalse(Files.exists(targetFile));
scpFileTransfer.download(sourceFile.toAbsolutePath().toString(), targetDir.toAbsolutePath().toString());
assertTrue(Files.exists(targetFile));
}
@Test
public void shouldSCPDownloadFileWithoutPathEscaping() throws IOException {
SCPFileTransfer scpFileTransfer = sshClient.newSCPFileTransfer();
assertFalse(targetFile.exists());
File file = tempFolder.newFile("new file.txt");
FileUtil.writeToFile(file, "Some content");
scpFileTransfer.download(tempFolder.getRoot().getAbsolutePath() + "/new file.txt", targetFile.getAbsolutePath());
assertTrue(targetFile.exists());
assertThat(FileUtil.readFromFile(targetFile), CoreMatchers.containsString("Some content"));
assertFalse(Files.exists(targetFile));
Path file = tempFolder.toPath().resolve("new file.txt");
FileUtil.writeToFile(file.toFile(), "Some content");
scpFileTransfer.download(tempFolder.toPath().toAbsolutePath() + "/new file.txt", targetFile.toAbsolutePath().toString());
assertTrue(Files.exists(targetFile));
assertThat(FileUtil.readFromFile(targetFile.toFile()), CoreMatchers.containsString("Some content"));
}
}