Mimic sftp connection disruption

54 Views Asked by At

I am attempting to abruptly disconnect from an SFTP connection in Java without using the sftp.disconnect() method. Using this to build an integration test that checks that clean up happens everytime. See the test below:

public void checkDisruptedConnections() throws JSchException, InterruptedException {
    ChannelSftp sftp = setupSftp(null);
    sftp.connect();

    try {
        //disrupt connection OVER HERE
    } catch (Exception e) {
        assertEquals("1", jedis.get(SESSION_KEY));
    }

    waitForConnectionClose();
    assertEquals("0", jedis.get(SESSION_KEY));
}
1

There are 1 best solutions below

0
Chognificent On

Ended up using a separate thread that connects and gets interupted.

@Test
public void testSftpInterupt() throws InterruptedException, JSchException, SftpException {
    Connect thread = new Connect();
    thread.start();

    while (thread.isAlive()) {
        waitForConnectionClose();
    }

    waitForConnectionClose();
    assertEquals("0", jedis.get(SESSION_KEY));
}

Connect looks as follows:

private class Connect extends Thread {
    @Override
    public void run() {
        ChannelSftp sftp = null;
        Thread thread = this;

        SftpProgressMonitor monitor = new SftpProgressMonitor() {
            @Override
            public void init(int op, String src, String dest, long max) {
            }

            @Override
            public boolean count(long count) {
                currentThread().interrupt();
                return false;
            }

            @Override
            public void end() {
            }
        };

        try {
            sftp.connect();
            sftp.put(LOCAL_FILE_LARGE, remoteFile, monitor);
        } catch (JSchException | SftpException e) {
            assertEquals("java.io.InterruptedIOException", e.getMessage());
        }
    }
}