diff options
Diffstat (limited to 'datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java')
-rw-r--r-- | datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java | 212 |
1 files changed, 126 insertions, 86 deletions
diff --git a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java index 9a4d045a..cb3735be 100644 --- a/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java +++ b/datafile-app-server/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java @@ -1,144 +1,184 @@ -/* +/*- * ============LICENSE_START====================================================================== * Copyright (C) 2018-2019 Nordix Foundation. All rights reserved. * =============================================================================================== - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. You may obtain a copy of the License at + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. + * Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions + * and limitations under the License. * ============LICENSE_END======================================================================== */ package org.onap.dcaegen2.collectors.datafile.ftp; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.apache.commons.io.IOUtils.toByteArray; -import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; -import com.github.stefanbirkner.fakesftpserver.rule.FakeSftpServerRule; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; import java.nio.file.Paths; -import org.junit.Rule; -import org.junit.Test; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; +@ExtendWith(MockitoExtension.class) public class SftpClientTest { + private static final String HOST = "127.0.0.1"; + private static final int SFTP_PORT = 1021; private static final String USERNAME = "bob"; private static final String PASSWORD = "123"; - private static final String DUMMY_CONTENT = "dummy content"; - private static final Path LOCAL_DUMMY_FILE = Paths.get("target/dummy.txt"); - private static final String REMOTE_DUMMY_FILE = "/dummy_directory/dummy_file.txt"; - private static final JSch JSCH = new JSch(); - private static final int TIMEOUT = 2000; - @Rule - public final FakeSftpServerRule sftpServer = new FakeSftpServerRule().addUser(USERNAME, PASSWORD); + @Mock + private JSch jschMock; + + @Mock + private Session sessionMock; + + @Mock + private ChannelSftp channelMock; @Test - public void collectFile_withOKresponse() - throws DatafileTaskException, IOException, JSchException, SftpException, Exception { + public void openWithPort_success() + throws DatafileTaskException, IOException, JSchException, SftpException, Exception { FileServerData expectedFileServerData = ImmutableFileServerData.builder() // - .serverAddress("127.0.0.1") // + .serverAddress(HOST) // .userId(USERNAME) // .password(PASSWORD) // - .port(sftpServer.getPort()) // + .port(SFTP_PORT) // .build(); - try (SftpClient sftpClient = new SftpClient(expectedFileServerData)) { - sftpClient.open(); - sftpServer.putFile(REMOTE_DUMMY_FILE, DUMMY_CONTENT, UTF_8); - byte[] file = downloadFile(sftpServer, REMOTE_DUMMY_FILE); - - sftpClient.collectFile(REMOTE_DUMMY_FILE, LOCAL_DUMMY_FILE); - byte[] localFile = Files.readAllBytes(LOCAL_DUMMY_FILE.toFile().toPath()); - assertThat(new String(file, UTF_8)).isEqualTo(DUMMY_CONTENT); - assertThat(new String(localFile, UTF_8)).isEqualTo(DUMMY_CONTENT); - } + + SftpClient sftpClientSpy = spy(new SftpClient(expectedFileServerData)); + + doReturn(jschMock).when(sftpClientSpy).createJsch(); + when(jschMock.getSession(anyString(), anyString(), anyInt())).thenReturn(sessionMock); + when(sessionMock.openChannel(anyString())).thenReturn(channelMock); + + sftpClientSpy.open(); + + verify(jschMock).getSession(USERNAME, HOST, SFTP_PORT); + verify(sessionMock).setConfig("StrictHostKeyChecking", "no"); + verify(sessionMock).setPassword(PASSWORD); + verify(sessionMock).connect(); + verify(sessionMock).openChannel("sftp"); + verifyNoMoreInteractions(sessionMock); + + verify(channelMock).connect(); + verifyNoMoreInteractions(channelMock); } @Test - public void collectFile_withWrongUserName_shouldFail() throws DatafileTaskException, IOException { + public void openWithoutPort_success() + throws DatafileTaskException, IOException, JSchException, SftpException, Exception { FileServerData expectedFileServerData = ImmutableFileServerData.builder() // - .serverAddress("127.0.0.1") // - .userId("wrong") // + .serverAddress(HOST) // + .userId(USERNAME) // .password(PASSWORD) // - .port(sftpServer.getPort()) // + .port(Optional.empty()) // .build(); - try (SftpClient sftpClient = new SftpClient(expectedFileServerData)) { - sftpServer.putFile(REMOTE_DUMMY_FILE, DUMMY_CONTENT, UTF_8); + SftpClient sftpClientSpy = spy(new SftpClient(expectedFileServerData)); - assertThatThrownBy(() -> sftpClient.open()) - .hasMessageContaining("Could not open Sftp clientcom.jcraft.jsch.JSchException: Auth fail"); - } + doReturn(jschMock).when(sftpClientSpy).createJsch(); + when(jschMock.getSession(anyString(), anyString(), anyInt())).thenReturn(sessionMock); + when(sessionMock.openChannel(anyString())).thenReturn(channelMock); + + sftpClientSpy.open(); + + verify(jschMock).getSession(USERNAME, HOST, 22); } @Test - public void collectFile_withWrongFileName_shouldFail() - throws IOException, JSchException, SftpException, DatafileTaskException { + public void open_throwsException() + throws DatafileTaskException, IOException, JSchException, SftpException, Exception { FileServerData expectedFileServerData = ImmutableFileServerData.builder() // - .serverAddress("127.0.0.1") // + .serverAddress(HOST) // .userId(USERNAME) // .password(PASSWORD) // - .port(sftpServer.getPort()) // + .port(SFTP_PORT) // .build(); - try (SftpClient sftpClient = new SftpClient(expectedFileServerData)) { - sftpServer.putFile(REMOTE_DUMMY_FILE, DUMMY_CONTENT, UTF_8); - sftpClient.open(); - assertThatThrownBy(() -> sftpClient.collectFile("wrong", LOCAL_DUMMY_FILE)) - .hasMessageStartingWith("Unable to get file from xNF. Data: FileServerData{serverAddress=127.0.0.1, " - + "userId=bob, password=123, port="); - } - } + SftpClient sftpClientSpy = spy(new SftpClient(expectedFileServerData)); - private static Session connectToServer(FakeSftpServerRule sftpServer) throws JSchException { - return connectToServerAtPort(sftpServer.getPort()); - } + doReturn(jschMock).when(sftpClientSpy).createJsch(); + when(jschMock.getSession(anyString(), anyString(), anyInt())).thenThrow(new JSchException("Failed")); - private static Session connectToServerAtPort(int port) throws JSchException { - Session session = createSessionWithCredentials(USERNAME, PASSWORD, port); - session.connect(TIMEOUT); - return session; + assertThatThrownBy(() -> sftpClientSpy.open()) + .hasMessageStartingWith("Could not open Sftp client. com.jcraft.jsch.JSchException: Failed"); } - private static ChannelSftp connectSftpChannel(Session session) throws JSchException { - ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); - channel.connect(); - return channel; - } + @SuppressWarnings("resource") + @Test + public void collectFile_succes() throws DatafileTaskException, SftpException { + FileServerData expectedFileServerData = ImmutableFileServerData.builder() // + .serverAddress(HOST) // + .userId(USERNAME) // + .password(PASSWORD) // + .port(SFTP_PORT) // + .build(); + SftpClient sftpClient = new SftpClient(expectedFileServerData); + + sftpClient.sftpChannel = channelMock; - private static Session createSessionWithCredentials(String username, String password, int port) - throws JSchException { - Session session = JSCH.getSession(username, "127.0.0.1", port); - session.setConfig("StrictHostKeyChecking", "no"); - session.setPassword(password); - return session; + sftpClient.collectFile("remote.xml", Paths.get("local.xml")); + + verify(channelMock).get("remote.xml", "local.xml"); + verifyNoMoreInteractions(channelMock); } - private static byte[] downloadFile(FakeSftpServerRule server, String path) - throws JSchException, SftpException, IOException { - Session session = connectToServer(server); - ChannelSftp channel = connectSftpChannel(session); - try { - InputStream is = channel.get(path); - return toByteArray(is); - } finally { - channel.disconnect(); - session.disconnect(); + @Test + public void collectFile_throwsExceptionWithoutRetry() + throws IOException, JSchException, SftpException, DatafileTaskException { + FileServerData expectedFileServerData = ImmutableFileServerData.builder() // + .serverAddress(HOST) // + .userId(USERNAME) // + .password(PASSWORD) // + .port(SFTP_PORT) // + .build(); + + try (SftpClient sftpClient = new SftpClient(expectedFileServerData)) { + sftpClient.sftpChannel = channelMock; + doThrow(new SftpException(ChannelSftp.SSH_FX_NO_SUCH_FILE, "Failed")).when(channelMock).get(anyString(), + anyString()); + + assertThatThrownBy(() -> sftpClient.collectFile("remoteFile", Paths.get("localFile"))) + .isInstanceOf(DatafileTaskException.class) + .hasMessageStartingWith("Unable to get file from xNF. Data: FileServerData{serverAddress=" + HOST + + ", " + "userId=" + USERNAME + ", password=####, port=" + SFTP_PORT); } } + + @Test + public void close_succes() throws DatafileTaskException, SftpException { + SftpClient sftpClient = new SftpClient(null); + + sftpClient.session = sessionMock; + sftpClient.sftpChannel = channelMock; + + sftpClient.close(); + + verify(sessionMock).disconnect(); + verifyNoMoreInteractions(sessionMock); + + verify(channelMock).exit();; + verifyNoMoreInteractions(channelMock); + } } |