GithubHelp home page GithubHelp logo

stefanbirkner / fake-sftp-server-rule Goto Github PK

View Code? Open in Web Editor NEW
40.0 3.0 26.0 88 KB

A JUnit rule that runs an in-memory SFTP server.

License: MIT License

Java 100.00%
sftp sftp-server junit-rule java test unittest inmemory

fake-sftp-server-rule's Introduction

Fake SFTP Server Rule

Build Status

Fake SFTP Server Rule is a JUnit rule that runs an in-memory SFTP server while your tests are running. It uses the SFTP server of the Apache SSHD project.

Fake SFTP Server Rule is published under the MIT license. It requires at least Java 8. Please open an issue if you want to use it with an older version of Java.

I want to thank my former team SAM at ThoughtWorks for using this library and @crizzis, @OArtyomov and @TheSentinel454 for their feature requests.

There is an alternative to Fake SFTP Server Rule that is independent of the test framework. Its name is Fake SFTP Server Lambda.

Installation

Fake SFTP Server Rule is available from Maven Central.

<dependency>
  <groupId>com.github.stefanbirkner</groupId>
  <artifactId>fake-sftp-server-rule</artifactId>
  <version>2.0.1</version>
</dependency>

If you upgrade from a version < 2.x to the newest version please read the last section of this readme.

Usage

The Fake SFTP Server Rule is used by adding it to your test class.

import com.github.stefanbirkner.fakesftpserver.rule.FakeSftpServerRule;

public class TestClass {
  @Rule
  public final FakeSftpServerRule sftpServer = new FakeSftpServerRule();

  ...
}

This rule starts a server before your test and stops it afterwards.

By default the SFTP server listens on an auto-allocated port. During the test this port can be obtained by sftpServer.getPort(). It can be changed by calling setPort(int). If you do this from within a test then the server gets restarted. The time-consuming restart can be avoided by setting the port immediately after creating the rule.

public class TestClass {
  @Rule
  public final FakeSftpServerRule sftpServer = new FakeSftpServerRule()
      .setPort(1234);

  ...
}

You can interact with the SFTP server by using the SFTP protocol with password authentication. By default the server accepts every pair of username and password, but you can restrict it to specific pairs.

public class TestClass {
  @Rule
  public final FakeSftpServerRule sftpServer = new FakeSftpServerRule()
      .addUser("username", "password");

  ...
}

It is also possible to do this during the test using the same method.

Testing code that reads files

If you test code that reads files from an SFTP server then you need a server that provides these files. Fake SFTP Server Rule provides a shortcut for uploading files to the server.

@Test
public void testTextFile() {
  sftpServer.putFile("/directory/file.txt", "content of file", UTF_8);
  //code that downloads the file
}

@Test
public void testBinaryFile() {
  byte[] content = createContent();
  sftpServer.putFile("/directory/file.bin", content);
  //code that downloads the file
}

Test data that is provided as an input stream can be uploaded directly from that input stream. This is very handy if your test data is available as a resource.

@Test
public void testFileFromInputStream() {
  InputStream is = getClass().getResourceAsStream("data.bin");
  sftpServer.putFile("/directory/file.bin", is);
  //code that downloads the file
}

If you need an empty directory then you can use the method createDirectory(String).

@Test
public void testDirectory() {
  sftpServer.createDirectory("/a/directory");
  //code that reads from or writes to that directory
}

You may create multiple directories at once with createDirectories(String...).

@Test
public void testDirectories() {
  sftpServer.createDirectories(
    "/a/directory",
    "/another/directory"
  );
  //code that reads from or writes to that directories
}

Testing code that writes files

If you test code that writes files to an SFTP server then you need to verify the upload. Fake SFTP Server Rule provides a shortcut for getting the file's content from the server.

@Test
public void testTextFile() {
  //code that uploads the file
  String fileContent = sftpServer.getFileContent("/directory/file.txt", UTF_8);
  ...
}

@Test
public void testBinaryFile() {
  //code that uploads the file
  byte[] fileContent = sftpServer.getFileContent("/directory/file.bin");
  ...
}

Testing existence of files

If you want to check whether a file hast been created or deleted then you can verify that it exists or not.

@Test
public void testFile() {
  //code that uploads or deletes the file
  boolean exists = sftpServer.existsFile("/directory/file.txt");
  ...
}

The method returns true iff the file exists and it is not a directory.

Delete all files

If you want to reuse the SFTP server then you can delete all files and directories on the SFTP server. (This is rarely necessary because the rule itself takes care that every test starts and ends with a clean SFTP server.)

sftpServer.deleteAllFilesAndDirectories()

Contributing

You have three options if you have a feature request, found a bug or simply have a question about Fake SFTP Server Rule.

Development Guide

Fake SFTP Server Rule is build with Maven. If you want to contribute code then

  • Please write a test for your change.
  • Ensure that you didn't break the build by running mvn verify -Dgpg.skip.
  • Fork the repo and create a pull request. (See Understanding the GitHub Flow)

The basic coding style is described in the EditorConfig file .editorconfig.

Fake SFTP Server Rule supports Travis CI for continuous integration. Your pull request will be automatically build by Travis CI.

Release Guide

  • Select a new version according to the Semantic Versioning 2.0.0 Standard.
  • Set the new version in pom.xml and in the Installation section of this readme.
  • Commit the modified pom.xml and README.md.
  • Run mvn clean deploy with JDK 8.
  • Add a tag for the release: git tag fake-sftp-server-rule-X.X.X

Upgrading from 0.x.y or 1.x.y to version >= 2

In older versions the SFTP server listened to port 23454 by default. From version 2 on it selects an arbitrary free port by default. If your tests fail after an upgrade you may consider to restore the old behaviour by immediately setting the old port after creating the rule.

@Rule
public final FakeSftpServerRule sftpServer = new FakeSftpServerRule()
    .setPort(23454);

fake-sftp-server-rule's People

Contributors

stefanbirkner avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

fake-sftp-server-rule's Issues

Support for user accounts/testing credentials

It would be a nice feature if we could interact with the server using actual user credentials.

At a minimum, the server could accept one specific set of credentials (rather than accepting any client-provided credentials). Alternatively, a flag could be set that indicates the server should now refuse any connection attempts, returning authorization error as the cause.

Support for junit 5

In junit 5 this library throws "test has not been started or is already finished" from verifyThatTestIsRunning method because of @rule is no more there in junit 5. so is there any other version compatible with Junit 5 ?

TestNG support

Hi There,

You fake-sftp-server-rule seems really interesting, but I was wondering how I can use in TestNG. Do I have to manually start and stop the server? And if so How would this be done?

Best regards,

Baubak

FakeSftpServerRule.createDirectory should accept a varargs parameter

Hi,

it would be awesome if createDirectory would accept a varargs String parameter, something like

public void createDirectory(String... paths) throws IOException {
    this.verifyThatTestIsRunning("create directory");
    Arrays.stream(paths).forEach(path -> {
        Path pathAsObject = this.fileSystem.getPath(path, new String[0]);
        Files.createDirectories(pathAsObject, new FileAttribute[0]);
    });
}

This way, the method would still be backwards compatible but creating multiple directories would be simplified.

ServiceConfigurationError when calling @Rule

Hi Stefan,

i was integrating your nice test tool fake-sftp-server-rule in our code and saldy got an exception.

  @Rule
  public final FakeSftpServerRule sftpServer = new FakeSftpServerRule().addUser("user", "pass");
ftpUloadFileFromFilesystem(de.itout.spinterface.interfaces.fileDistributor.FileDistributorSFTPUploadTest)  Time elapsed: 1.084 sec  <<< ERROR!
java.util.ServiceConfigurationError: java.nio.file.spi.FileSystemProvider: Provider org.apache.sshd.client.subsystem.sftp.SftpFileSystemProvider could not be instantiated
	at java.util.ServiceLoader.fail(ServiceLoader.java:232)
	at java.util.ServiceLoader.access$100(ServiceLoader.java:185)
	at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:384)
	at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
	at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
	at java.nio.file.spi.FileSystemProvider.loadInstalledProviders(FileSystemProvider.java:119)
	at java.nio.file.spi.FileSystemProvider.access$000(FileSystemProvider.java:77)
	at java.nio.file.spi.FileSystemProvider$1.run(FileSystemProvider.java:169)
	at java.nio.file.spi.FileSystemProvider$1.run(FileSystemProvider.java:166)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.nio.file.spi.FileSystemProvider.installedProviders(FileSystemProvider.java:166)
	at java.nio.file.FileSystems.newFileSystem(FileSystems.java:324)
	at com.github.marschall.memoryfilesystem.MemoryFileSystemBuilder.build(MemoryFileSystemBuilder.java:505)
	at com.github.stefanbirkner.fakesftpserver.rule.FakeSftpServerRule.createFileSystem(FakeSftpServerRule.java:421)
	at com.github.stefanbirkner.fakesftpserver.rule.FakeSftpServerRule.access$000(FakeSftpServerRule.java:158)
	at com.github.stefanbirkner.fakesftpserver.rule.FakeSftpServerRule$2.evaluate(FakeSftpServerRule.java:403)
	at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
	at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
	at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:298)
	at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
	at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
	at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:218)
	at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:160)
	at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:134)
	at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
	at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
	at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:136)
	at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:117)
	at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:57)
	at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
	at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
	at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
	at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
	at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
	at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
	at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
	at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.ClassCastException: Cannot cast org.apache.sshd.common.util.security.bouncycastle.BouncyCastleSecurityProviderRegistrar to org.apache.sshd.common.util.security.SecurityProviderRegistrar
	at java.lang.Class.cast(Class.java:3369)
	at org.apache.sshd.common.util.threads.ThreadUtils.createDefaultInstance(ThreadUtils.java:114)
	at org.apache.sshd.common.util.threads.ThreadUtils.createDefaultInstance(ThreadUtils.java:121)
	at org.apache.sshd.common.util.threads.ThreadUtils.createDefaultInstance(ThreadUtils.java:107)
	at org.apache.sshd.common.util.security.SecurityUtils.register(SecurityUtils.java:397)
	at org.apache.sshd.common.util.security.SecurityUtils.isEDDSACurveSupported(SecurityUtils.java:529)
	at org.apache.sshd.common.signature.BuiltinSignatures$6.isSupported(BuiltinSignatures.java:103)
	at org.apache.sshd.common.NamedFactory.lambda$setUpBuiltinFactories$1(NamedFactory.java:63)
	at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174)
	at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:566)
	at org.apache.sshd.common.NamedFactory.setUpBuiltinFactories(NamedFactory.java:64)
	at org.apache.sshd.common.BaseBuilder.setUpDefaultSignatures(BaseBuilder.java:339)
	at org.apache.sshd.common.BaseBuilder.fillWithDefaultValues(BaseBuilder.java:159)
	at org.apache.sshd.client.ClientBuilder.fillWithDefaultValues(ClientBuilder.java:103)
	at org.apache.sshd.client.ClientBuilder.fillWithDefaultValues(ClientBuilder.java:49)
	at org.apache.sshd.common.BaseBuilder.build(BaseBuilder.java:265)
	at org.apache.sshd.client.ClientBuilder.build(ClientBuilder.java:146)
	at org.apache.sshd.client.ClientBuilder.build(ClientBuilder.java:49)
	at org.apache.sshd.common.BaseBuilder.build(BaseBuilder.java:288)
	at org.apache.sshd.client.SshClient.setUpDefaultClient(SshClient.java:790)
	at org.apache.sshd.client.subsystem.sftp.SftpFileSystemProvider.<init>(SftpFileSystemProvider.java:157)
	at org.apache.sshd.client.subsystem.sftp.SftpFileSystemProvider.<init>(SftpFileSystemProvider.java:149)
	at org.apache.sshd.client.subsystem.sftp.SftpFileSystemProvider.<init>(SftpFileSystemProvider.java:135)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at java.lang.Class.newInstance(Class.java:442)
	at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
	... 39 more

Known host file not configured, using user known host file: C:\Users\Sam/.ssh/known_hosts

Error while trying to do sftp.

Caused by: com.jcraft.jsch.JSchException: java.io.FileNotFoundException: C:\Users\Sam.ssh\known_hosts (The system cannot find the path specified)
at com.jcraft.jsch.KnownHosts.setKnownHosts(KnownHosts.java:57)
at com.jcraft.jsch.JSch.setKnownHosts(JSch.java:317)
at org.apache.camel.component.file.remote.SftpOperations.createSession(SftpOperations.java:286)
at org.apache.camel.component.file.remote.SftpOperations.connect(SftpOperations.java:115)
... 76 more

In actual sftp server it works fine , but on this mock , the connection could not get established

Getting Software caused connection abort: socket write error

Hi I am trying to integrate this fake-sftp-server-rule with my JUnits.

I started fake-sftp-server-rule and trying to make a connection with my client but I am facing below error.

com.jcraft.jsch.JSchException: java.net.SocketException: Software caused connection abort: socket write error

at com.jcraft.jsch.ChannelSftp.start(ChannelSftp.java:315)
at com.jcraft.jsch.Channel.connect(Channel.java:152)
at com.jcraft.jsch.Channel.connect(Channel.java:145)

fakesftpserver.txt

Attached the sample code snippet, Can you please help me connecting to sftp server and make uploads and download.

Thanks in advance,
Dinesh

multiple errors

I'm gettin an error when trying to create a directory, put a file

Creating directory:

Error auto creating directory: folder due File operation failed: Could not parse response code.
Server Reply: SSH-2.0-SSHD-CORE-1.7.0. Code: 0. This exception is ignored.

Reading file:

Caused by: org.apache.commons.net.MalformedServerReplyException: Could not parse response code.
Server Reply: SSH-2.0-SSHD-CORE-1.7.0

When disconnecting:

Error occurred while disconnecting from ftps://admin@localhost:12345 due: File operation failed: Could not parse response code.
Server Reply: Unsupported protocol version: QUIT
. Code: 0. This exception will be ignored.

This is how I declare it:

@Rule
    public final FakeSftpServerRule sftpServer = new FakeSftpServerRule()
            .setPort(12345)
            .addUser("admin", "admin");

and this is how I create folder and put file, in @PostConstruct method:

sftpServer.createDirectory("/folder");
        sftpServer.putFile("/folder/myfile_20180115082245.csv", CSV_CONTENTS, StandardCharsets.UTF_8);

The file is read by apache camel ftp, using this route:
ftps://admin@localhost:12345/folder?binary=true&connectTimeout=5000

How to simulate failure scenario ?

The source code that I am creating unit tests has a lot of try catch block. How do I simulate failure scenario, so I can cover those catch blocks ? Is there I way we can customize the response or reply code of the different SFTP commands ?

Set file modification time during upload

I'm running a test suite where the modification time of a file is taken into account. Currently I have to add a Thread.sleep in order for these times to be different. It seems it is possible to set the modification time of a file using the BasicFileAttributeView It would be nice to be able to set the modification time during upload. (Maybe the creation time and last accessed time as well, but I don't know if they are supported by the underlying filesystem.)

SSH key support

The rule is working fine but I'd like to use it also with an identity file.
Would you mind a PR on this topic?

The aim is to support authentication via an SSH public/private key pair.

If it's ok for you then there is already an implementation in #15

incompatibility with sshd-core 2.0.0

gradle now pulls in sshd-core 2.0.0 as depndency which is not compatible.

./gradlew dependencyInsight --configuration testCompile --dependency sshd

org.apache.sshd:sshd-core:[1,) -> 2.0.0
variant "runtime"
--- com.github.stefanbirkner:fake-sftp-server-rule:2.0.0
--- testCompile

with SSHD-815, the sftp component has been moved into its own module and org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory no longer exists in sshd-core.
this project needs to start declaring sshd-sftp as dependency or restrict the version of sshd-core to below 2.0.0

pom dependency error com.github.marschall 1.0.1-SNAPSHOT

Hi,

Thanks a lot for this rule, it is a great help for me, and testing my project.

I think recently, the version of dependency com.github.marschall rose to 1.0.1-SNAPSHOT and my project can't compile anymore.

[ERROR] Failed to execute goal on project common: Could not resolve dependencies for project ..*:common:jar:0.0.1-SNAPSHOT: Could not find artifact com.github.marschall:memoryfilesystem:jar:1.0.1-SNAPSHOT -> [Help 1]

I was able to resolve it by excluding the dependency in your module, and importing version 1.0.0 of com.github.marschall.

Cleaning file system

Could you create public method in FakeSftpServerRule for clean file system ?

Example of code


 public void clearFileSystem() {
        Iterable<Path> rootDirectories = fileSystem.getRootDirectories();
        if (rootDirectories != null) {
            stream(rootDirectories.spliterator(), false)
                    .forEach(path -> {
                        try {
                            walkFileTree(path, new SimpleFileVisitor<Path>() {

                                @Override
                                public FileVisitResult visitFile(Path file,
                                                                 BasicFileAttributes attrs) throws IOException {
                                    deleteContent(file);
                                    return CONTINUE;
                                }

                                private void deleteContent(Path file) throws IOException {
                                    if (file.getNameCount() != 0) {
                                        Files.delete(file);
                                    }
                                }

                                @Override
                                public FileVisitResult postVisitDirectory(Path dir, IOException exc)
                                        throws IOException {
                                    deleteContent(dir);
                                    return CONTINUE;
                                }
                            });
                        } catch (IOException e) {
                            log.error("Error during delete content", e);
                        }
                    });
        }
    }

PowerMock and FakeSftpServerRule Server wont start

I have a worst case scenario application i have to write unit test for.
Much static & legacy code.
I managed to get it running by powermock static methods.
One Unit test has to run against a SFTP Server.
I tried your rule in a clean env. and it works as designed.
But when i add it to our code, the server wont start. (Tired with FileZilla to connect to the random port).

package de.itout.spinterface.interfaces.fileDistributor;

import com.github.stefanbirkner.fakesftpserver.rule.*;
import de.gsq.system.*;
import de.itout.spinterfaces.*;
import de.itout.spinterfaces.interfaces.*;
import java.io.*;
import java.net.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.util.*;
import org.junit.*;
import static org.junit.Assert.*;
import org.junit.runner.*;
import static org.mockito.Mockito.*;
import org.powermock.api.mockito.*;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.junit4.*;

/**
 * Unit Test der Schnittstelle FileDistributor.
 *
 * Testcase: File SFTP Upload.
 *
 * @author swendelmann
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(VO.class)
@PowerMockIgnore(
  {
    "javax.management.*", "javax.script.*", "org.apache.sshd.*", "com.github.*"
  })
public class FileDistributorSFTPUploadTest
{

  /**
   * Interface to Test.
   */
  private SPInterface inter;

  @Rule
  public final FakeSftpServerRule sftpServer = new FakeSftpServerRule().addUser("username", "password");

  private final String sftpDir = "/data";
  private final String sftpUser = "username";
  private final String sftpPass = "password";
  private File testFile;

  public FileDistributorSFTPUploadTest()
  {
  }

  @Before
  public void setUp() throws URISyntaxException, IOException
  {
    Environment.getInstance().setApplicationType(Environment.APPLICATION_TYPE_CLI);

    PowerMockito.mockStatic(VO.class);
    PowerMockito.when(VO.getVO(anyString())).thenReturn("mocked");
    PowerMockito.when(VO.getVO(anyString(), any(Object[].class))).thenReturn("mocked");
    PowerMockito.when(VO.getVO(anyString(), any(Object[].class), anyString())).thenReturn("mocked");
    PowerMockito.when(VO.getVO(anyString(), any(Class.class))).thenReturn("mocked");
    PowerMockito.when(VO.getVOEntry(anyString(), anyString(), anyString(), any(Object[].class), anyString(), anyString())).thenReturn("mocked");

    // Interface Setup
    inter = new FileDistributor();
    inter.setLaufID("FD00002");
    inter.setSchnittstelle("FileDist");
    inter.setVersion("FD02");

    testFile = new File(getClass().getClassLoader().getResource("order.csv").toURI());

    sftpServer.createDirectory(sftpDir);

  }

  @After
  public void tearDown()
  {
  }

  @Test
  public void ftpUloadFileFromFilesystem() throws URISyntaxException, IOException
  {
    // Init Interface Parameter
    HashMap<String, SPInterface.ParameterHeader> header = new HashMap<>();
    LinkedHashMap<String, SPParameter> parameter = new LinkedHashMap<>();
    header.put("SAVE_DIC", inter.new ParameterHeader("A", 1, "Sicherungsverzeichnis"));
    header.put("IN_DIR", inter.new ParameterHeader("A", 1, "Input Verzeichnis"));
    header.put("FILESEL", inter.new ParameterHeader("A", 1, "Datei Selection"));
    header.put("SFTP", inter.new ParameterHeader("A", 1, "SFTP übertragen?"));
    header.put("SFTPDIR", inter.new ParameterHeader("A", 1, "SFTP Verz"));
    header.put("SFTPHOST", inter.new ParameterHeader("A", 1, "SFTP host"));
    header.put("SFTPPORT", inter.new ParameterHeader("A", 1, "SFTP Port"));
    header.put("SFTPUSER", inter.new ParameterHeader("A", 1, "SFTP User"));
    header.put("SFTPPWD", inter.new ParameterHeader("A", 1, "SFTP PWD"));

    parameter.put("SAVE_DIC_1", new SPParameter("A", "test-save-dic", 0, "", "Sicherungsverzeichnis"));
    parameter.put("IN_DIR_1", new SPParameter("A", testFile.getParent(), 0, "", "Input Verzeichnis"));
    parameter.put("FILESEL_1", new SPParameter("A", testFile.getName(), 0, "", "Datei Selection"));
    parameter.put("SFTP_1", new SPParameter("A", "JA", 0, "", "SFTP übertragen?"));
    parameter.put("SFTPDIR_1", new SPParameter("A", sftpDir, 0, "", "SFTP Verz"));
    parameter.put("SFTPHOST_1", new SPParameter("A", "localhost", 0, "", "SFTP host"));
    parameter.put("SFTPPORT_1", new SPParameter("A", "", sftpServer.getPort(), "", "SFTP Port"));
    parameter.put("SFTPUSER_1", new SPParameter("A", sftpUser, 0, "", "SFTP User"));
    parameter.put("SFTPPWD_1", new SPParameter("A", sftpPass, 0, "", "SFTP PWD"));
    inter.loadTestParameter(header, parameter);

    inter.startTest();

    // Assertions
    // Assert Interface Values (status, appended files, logging, etc.)
    assertEquals(SPInterface.OK, inter.getLaufStatus());
    assertTrue(inter.getLaufDateien().stream().filter(o -> o.getDatei().equals(testFile.getName())).findFirst().isPresent());
    assertTrue(sftpServer.existsFile(sftpDir + "/order.csv"));
    assertEquals("A;B;C", sftpServer.getFileContent(sftpDir + "/order.csv", UTF_8));

    //TODO: Weitere Assertions definieren.
  }

}

The Output

Running de.itout.spinterface.interfaces.fileDistributor.FileDistributorSFTPUploadTest
ERROR StatusLogger Unrecognized format specifier [d]
ERROR StatusLogger Unrecognized conversion specifier [d] starting at position 16 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [thread]
ERROR StatusLogger Unrecognized conversion specifier [thread] starting at position 25 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [level]
ERROR StatusLogger Unrecognized conversion specifier [level] starting at position 35 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [logger]
ERROR StatusLogger Unrecognized conversion specifier [logger] starting at position 47 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [msg]
ERROR StatusLogger Unrecognized conversion specifier [msg] starting at position 54 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [n]
ERROR StatusLogger Unrecognized conversion specifier [n] starting at position 56 in conversion pattern.
ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2
ERROR StatusLogger Unrecognized format specifier [d]
ERROR StatusLogger Unrecognized conversion specifier [d] starting at position 16 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [thread]
ERROR StatusLogger Unrecognized conversion specifier [thread] starting at position 25 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [level]
ERROR StatusLogger Unrecognized conversion specifier [level] starting at position 35 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [logger]
ERROR StatusLogger Unrecognized conversion specifier [logger] starting at position 47 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [msg]
ERROR StatusLogger Unrecognized conversion specifier [msg] starting at position 54 in conversion pattern.
ERROR StatusLogger Unrecognized format specifier [n]
ERROR StatusLogger Unrecognized conversion specifier [n] starting at position 56 in conversion pattern.

Get a directory listing or use wildcard with existsFile

feature request

I need to test if a file has been created without knowing the exact name of the file. The existsFile() function does almost what I need but only works using an exact path and file name.

The scenario is that the application is placing a file in a particular SFTP folder and adding a timestamp to the file name. The path to the folder is known and part of the file name is known, but the timestamp included in the file name is not exactly predictable.

Could it be possible to use a glob pattern wildcard? For example existsFile("/path/*_file.txt")

Alternatively, could it be possible to retrieve a directory listing? For example: listDirectory("/path"). I could then check the result to see if the file is present.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.