Test FTP usage?


When depending on a FTP in production we often simulate it through a
local file in dev and sometimes in preprod. That’s great and avoid to
need a big infra in all environment but make ftp dependencies optional
before the prod…so you risk to clean them and miss them in prod.

To avoid it it is easy to test FTP through JUnit using MockFtp project.

First add the following maven dependencies:

<dependency>
<groupId>org.mockftpserver</groupId>
<artifactId>MockFtpServer</artifactId>
<version>2.4</version>
<scope>test</scope>
</dependency>

Then to create your test ftp server you need:

  • To create its filesystem (unix or windows styles whatever is your
    current environment :))
  • Create a server with previous filesystem
  • Add user(s) to your server

Here how it can look like:

final
FileSystem fileSystem = new UnixFakeFileSystem();
fileSystem.add(new DirectoryEntry("/data"));
fileSystem.add(new FileEntry("/data/foo.txt"));

server = new FakeFtpServer();
server.addUserAccount(new UserAccount("test", "testpwd",
"/data"));
server.setFileSystem(fileSystem);

server.start();
try {
  final
FileObject[] children = doProducerFtp();
  assertEquals(1,
children.length);
  assertEquals("/data/foo.txt", children[0].getName().getPath());
} finally {
  server.stop();
}

Of course start/stop can be done in @Before/@After if you prefer.

Not this will surely not stop because of the default port used by the
server + on CI platform you need to use random ports. I’m not sure
this is expected but since MockFtpServer is backed by a ServerSocket
(java one) you can simply force its port to 0 and a random will be
used:

server.setServerControlPort(0);

Now you have this test, if your build is passing you are sure you’ll
not miss a ftp class in prod 🙂 (You can still want to add security
etc to enforce it).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s