diff options
Diffstat (limited to 'datafile-dmaap-client/src/test')
7 files changed, 0 insertions, 786 deletions
diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/FtpsClientTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/FtpsClientTest.java deleted file mode 100644 index 9e6c29f8..00000000 --- a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/FtpsClientTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * ============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 - * - * 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. - * ============LICENSE_END======================================================================== - */ - -package org.onap.dcaegen2.collectors.datafile.ftp; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Path; -import java.nio.file.Paths; - -import javax.net.ssl.KeyManager; -import javax.net.ssl.TrustManager; - -import org.apache.commons.net.ftp.FTP; -import org.apache.commons.net.ftp.FTPSClient; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentMatchers; -import org.springframework.http.HttpStatus; - -public class FtpsClientTest { - - private static final String REMOTE_FILE_PATH = "/dir/sample.txt"; - private static final Path LOCAL_FILE_PATH = Paths.get("target/sample.txt"); - private static final String XNF_ADDRESS = "127.0.0.1"; - private static final int PORT = 8021; - private static final String FTP_KEY_PATH = "ftpKeyPath"; - private static final String FTP_KEY_PASSWORD = "ftpKeyPassword"; - private static final Path TRUSTED_CA_PATH = Paths.get("trustedCAPath"); - private static final String TRUSTED_CA_PASSWORD = "trustedCAPassword"; - - private static final String USERNAME = "bob"; - private static final String PASSWORD = "123"; - - - private FTPSClient ftpsClientMock = mock(FTPSClient.class); - private KeyManager keyManagerMock = mock(KeyManager.class); - private TrustManager trustManagerMock = mock(TrustManager.class); - private InputStream inputStreamMock = mock(InputStream.class); - private OutputStream outputStreamMock = mock(OutputStream.class); - - FtpsClient clientUnderTestSpy; - - private ImmutableFileServerData createFileServerData() { - return ImmutableFileServerData.builder().serverAddress(XNF_ADDRESS).userId(USERNAME).password(PASSWORD) - .port(PORT).build(); - } - - @BeforeEach - protected void setUp() throws Exception { - clientUnderTestSpy = spy(new FtpsClient(createFileServerData(), FTP_KEY_PATH, FTP_KEY_PASSWORD, TRUSTED_CA_PATH, - TRUSTED_CA_PASSWORD)); - clientUnderTestSpy.realFtpsClient = ftpsClientMock; - } - - private void verifyFtpsClientMock_openOK() throws Exception { - doReturn(outputStreamMock).when(clientUnderTestSpy).createOutputStream(LOCAL_FILE_PATH); - - when(ftpsClientMock.retrieveFile(ArgumentMatchers.eq(REMOTE_FILE_PATH), - ArgumentMatchers.any(OutputStream.class))).thenReturn(true); - verify(ftpsClientMock).setNeedClientAuth(true); - verify(ftpsClientMock).setKeyManager(keyManagerMock); - verify(ftpsClientMock).setTrustManager(trustManagerMock); - verify(ftpsClientMock).connect(XNF_ADDRESS, PORT); - verify(ftpsClientMock).login(USERNAME, PASSWORD); - verify(ftpsClientMock).getReplyCode(); - verify(ftpsClientMock, times(1)).enterLocalPassiveMode(); - verify(ftpsClientMock).execPBSZ(0); - verify(ftpsClientMock).execPROT("P"); - verify(ftpsClientMock).setFileType(FTP.BINARY_FILE_TYPE); - verify(ftpsClientMock).setBufferSize(1024 * 1024); - } - - @Test - public void collectFile_allOk() throws Exception { - - doReturn(keyManagerMock).when(clientUnderTestSpy).createKeyManager(FTP_KEY_PATH, FTP_KEY_PASSWORD); - doReturn(trustManagerMock).when(clientUnderTestSpy).getTrustManager(TRUSTED_CA_PATH, TRUSTED_CA_PASSWORD); - doReturn(outputStreamMock).when(clientUnderTestSpy).createOutputStream(LOCAL_FILE_PATH); - doReturn(true).when(ftpsClientMock).login(USERNAME, PASSWORD); - doReturn(HttpStatus.OK.value()).when(ftpsClientMock).getReplyCode(); - - clientUnderTestSpy.open(); - - doReturn(true).when(ftpsClientMock).retrieveFile(REMOTE_FILE_PATH, outputStreamMock); - clientUnderTestSpy.collectFile(REMOTE_FILE_PATH, LOCAL_FILE_PATH); - - doReturn(true).when(ftpsClientMock).isConnected(); - clientUnderTestSpy.close(); - - verifyFtpsClientMock_openOK(); - verify(ftpsClientMock, times(1)).isConnected(); - verify(ftpsClientMock, times(1)).logout(); - verify(ftpsClientMock, times(1)).disconnect(); - verify(ftpsClientMock, times(1)).retrieveFile(ArgumentMatchers.eq(REMOTE_FILE_PATH), any()); - verifyNoMoreInteractions(ftpsClientMock); - } - - @Test - public void collectFileFaultyOwnKey_shouldFail() throws Exception { - - doReturn(outputStreamMock).when(clientUnderTestSpy).createOutputStream(LOCAL_FILE_PATH); - assertThatThrownBy(() -> clientUnderTestSpy.open()) - .hasMessageContaining("Could not open connection: java.io.FileNotFoundException:"); - - verify(ftpsClientMock).setNeedClientAuth(true); - - doReturn(false).when(ftpsClientMock).isConnected(); - clientUnderTestSpy.close(); - verify(ftpsClientMock).isConnected(); - verifyNoMoreInteractions(ftpsClientMock); - } - - @Test - public void collectFileFaultTrustedCA_shouldFail_no_trustedCA_file() throws Exception { - - doReturn(keyManagerMock).when(clientUnderTestSpy).createKeyManager(FTP_KEY_PATH, FTP_KEY_PASSWORD); - doThrow(new IOException("problem")).when(clientUnderTestSpy).createInputStream(TRUSTED_CA_PATH); - - assertThatThrownBy(() -> clientUnderTestSpy.open()) - .hasMessage("Could not open connection: java.io.IOException: problem"); - } - - @Test - public void collectFileFaultTrustedCA_shouldFail_empty_trustedCA_file() throws Exception { - - doReturn(keyManagerMock).when(clientUnderTestSpy).createKeyManager(FTP_KEY_PATH, FTP_KEY_PASSWORD); - doReturn(inputStreamMock).when(clientUnderTestSpy).createInputStream(TRUSTED_CA_PATH); - - assertThatThrownBy(() -> clientUnderTestSpy.open()) - .hasMessage("Could not open connection: java.io.EOFException"); - } - - @Test - public void collectFileFaultyLogin_shouldFail() throws Exception { - - doReturn(keyManagerMock).when(clientUnderTestSpy).createKeyManager(FTP_KEY_PATH, FTP_KEY_PASSWORD); - doReturn(trustManagerMock).when(clientUnderTestSpy).getTrustManager(TRUSTED_CA_PATH, TRUSTED_CA_PASSWORD); - doReturn(outputStreamMock).when(clientUnderTestSpy).createOutputStream(LOCAL_FILE_PATH); - doReturn(false).when(ftpsClientMock).login(USERNAME, PASSWORD); - - assertThatThrownBy(() -> clientUnderTestSpy.open()).hasMessage("Unable to log in to xNF. 127.0.0.1"); - - verify(ftpsClientMock).setNeedClientAuth(true); - verify(ftpsClientMock).setKeyManager(keyManagerMock); - verify(ftpsClientMock).setTrustManager(trustManagerMock); - verify(ftpsClientMock).connect(XNF_ADDRESS, PORT); - verify(ftpsClientMock).login(USERNAME, PASSWORD); - } - - @Test - public void collectFileBadRequestResponse_shouldFail() throws Exception { - doReturn(keyManagerMock).when(clientUnderTestSpy).createKeyManager(FTP_KEY_PATH, FTP_KEY_PASSWORD); - doReturn(trustManagerMock).when(clientUnderTestSpy).getTrustManager(TRUSTED_CA_PATH, TRUSTED_CA_PASSWORD); - doReturn(outputStreamMock).when(clientUnderTestSpy).createOutputStream(LOCAL_FILE_PATH); - doReturn(true).when(ftpsClientMock).login(USERNAME, PASSWORD); - doReturn(503).when(ftpsClientMock).getReplyCode(); - - assertThatThrownBy(() -> clientUnderTestSpy.open()) - .hasMessage("Unable to connect to xNF. 127.0.0.1 xNF reply code: 503"); - - verify(ftpsClientMock).setNeedClientAuth(true); - verify(ftpsClientMock).setKeyManager(keyManagerMock); - verify(ftpsClientMock).setTrustManager(trustManagerMock); - verify(ftpsClientMock).connect(XNF_ADDRESS, PORT); - verify(ftpsClientMock).login(USERNAME, PASSWORD); - verify(ftpsClientMock, times(2)).getReplyCode(); - verifyNoMoreInteractions(ftpsClientMock); - } - - @Test - public void collectFile_shouldFail() throws Exception { - doReturn(keyManagerMock).when(clientUnderTestSpy).createKeyManager(FTP_KEY_PATH, FTP_KEY_PASSWORD); - doReturn(trustManagerMock).when(clientUnderTestSpy).getTrustManager(TRUSTED_CA_PATH, TRUSTED_CA_PASSWORD); - doReturn(outputStreamMock).when(clientUnderTestSpy).createOutputStream(LOCAL_FILE_PATH); - doReturn(true).when(ftpsClientMock).login(USERNAME, PASSWORD); - doReturn(HttpStatus.OK.value()).when(ftpsClientMock).getReplyCode(); - clientUnderTestSpy.open(); - - doReturn(false).when(ftpsClientMock).retrieveFile(REMOTE_FILE_PATH, outputStreamMock); - - assertThatThrownBy(() -> clientUnderTestSpy.collectFile(REMOTE_FILE_PATH, LOCAL_FILE_PATH)) - .hasMessage("Could not retrieve file /dir/sample.txt"); - - verifyFtpsClientMock_openOK(); - verify(ftpsClientMock, times(1)).retrieveFile(ArgumentMatchers.eq(REMOTE_FILE_PATH), any()); - verifyNoMoreInteractions(ftpsClientMock); - } - - @Test - public void collectFile_shouldFail_ioexception() throws Exception { - doReturn(keyManagerMock).when(clientUnderTestSpy).createKeyManager(FTP_KEY_PATH, FTP_KEY_PASSWORD); - doReturn(trustManagerMock).when(clientUnderTestSpy).getTrustManager(TRUSTED_CA_PATH, TRUSTED_CA_PASSWORD); - doReturn(outputStreamMock).when(clientUnderTestSpy).createOutputStream(LOCAL_FILE_PATH); - doReturn(true).when(ftpsClientMock).login(USERNAME, PASSWORD); - doReturn(HttpStatus.OK.value()).when(ftpsClientMock).getReplyCode(); - clientUnderTestSpy.open(); - when(ftpsClientMock.isConnected()).thenReturn(false); - - doThrow(new IOException("problem")).when(ftpsClientMock).retrieveFile(REMOTE_FILE_PATH, outputStreamMock); - - assertThatThrownBy(() -> clientUnderTestSpy.collectFile(REMOTE_FILE_PATH, LOCAL_FILE_PATH)) - .hasMessage("Could not fetch file: java.io.IOException: problem"); - - verifyFtpsClientMock_openOK(); - verify(ftpsClientMock, times(1)).retrieveFile(ArgumentMatchers.eq(REMOTE_FILE_PATH), any()); - verifyNoMoreInteractions(ftpsClientMock); - } -} diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SchemeTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SchemeTest.java deleted file mode 100644 index 162a0e78..00000000 --- a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SchemeTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 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 - * - * 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. - * ============LICENSE_END========================================================= - */ - -package org.onap.dcaegen2.collectors.datafile.ftp; - -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - -import org.junit.jupiter.api.Test; -import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; - -/** - * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a> - * - */ -public class SchemeTest { - @Test - public void getSchemeFromString_properScheme() throws DatafileTaskException { - - Scheme actualScheme = Scheme.getSchemeFromString("FTPES"); - assertEquals(Scheme.FTPS, actualScheme); - - actualScheme = Scheme.getSchemeFromString("FTPS"); - assertEquals(Scheme.FTPS, actualScheme); - - actualScheme = Scheme.getSchemeFromString("SFTP"); - assertEquals(Scheme.SFTP, actualScheme); - } - - @Test - public void getSchemeFromString_invalidScheme() { - assertTrue(assertThrows(DatafileTaskException.class, () -> Scheme.getSchemeFromString("invalid")).getMessage() - .startsWith("DFC does not support protocol invalid")); - } -} diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java deleted file mode 100644 index 85a0c090..00000000 --- a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/ftp/SftpClientTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * ============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 - * - * 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. - * ============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 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 org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; - -public class SftpClientTest { - 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); - - @Test - public void collectFile_withOKresponse() - throws DatafileTaskException, IOException, JSchException, SftpException, Exception { - FileServerData expectedFileServerData = ImmutableFileServerData.builder().serverAddress("127.0.0.1") - .userId(USERNAME).password(PASSWORD).port(sftpServer.getPort()).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); - } - } - - @Test - public void collectFile_withWrongUserName_shouldFail() throws DatafileTaskException, IOException { - FileServerData expectedFileServerData = ImmutableFileServerData.builder().serverAddress("127.0.0.1") - .userId("wrong").password(PASSWORD).port(sftpServer.getPort()).build(); - try (SftpClient sftpClient = new SftpClient(expectedFileServerData)) { - - sftpServer.putFile(REMOTE_DUMMY_FILE, DUMMY_CONTENT, UTF_8); - - - assertThatThrownBy(() -> sftpClient.open()) - .hasMessageContaining("Could not open Sftp clientcom.jcraft.jsch.JSchException: Auth fail"); - } - } - - @Test - public void collectFile_withWrongFileName_shouldFail() - throws IOException, JSchException, SftpException, DatafileTaskException { - FileServerData expectedFileServerData = ImmutableFileServerData.builder().serverAddress("127.0.0.1") - .userId(USERNAME).password(PASSWORD).port(sftpServer.getPort()).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="); - } - } - - private static Session connectToServer(FakeSftpServerRule sftpServer) throws JSchException { - return connectToServerAtPort(sftpServer.getPort()); - } - - private static Session connectToServerAtPort(int port) throws JSchException { - Session session = createSessionWithCredentials(USERNAME, PASSWORD, port); - session.connect(TIMEOUT); - return session; - } - - private static ChannelSftp connectSftpChannel(Session session) throws JSchException { - ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); - channel.connect(); - return channel; - } - - 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; - } - - 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(); - } - } -} diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/DmaapReactiveWebClientTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/DmaapReactiveWebClientTest.java deleted file mode 100644 index 54db7401..00000000 --- a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/DmaapReactiveWebClientTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * ============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 - * - * 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. - * ============LICENSE_END======================================================================== - */ - -package org.onap.dcaegen2.collectors.datafile.service; - -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.Mock; - - -import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapConsumerConfiguration; -import org.springframework.web.reactive.function.client.WebClient; - -class DmaapReactiveWebClientTest { - - @Mock - private DmaapConsumerConfiguration dmaapConsumerConfiguration; - - @BeforeEach - void setUp() { - dmaapConsumerConfiguration = mock(DmaapConsumerConfiguration.class); - } - - - @Test - void buildsDMaaPReactiveWebClientProperly() { - when(dmaapConsumerConfiguration.dmaapContentType()).thenReturn("*/*"); - WebClient dmaapReactiveWebClient = new DmaapReactiveWebClient() - .fromConfiguration(dmaapConsumerConfiguration) - .build(); - - verify(dmaapConsumerConfiguration, times(1)).dmaapContentType(); - assertNotNull(dmaapReactiveWebClient); - } -}
\ No newline at end of file diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/HttpUtilsTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/HttpUtilsTest.java deleted file mode 100644 index c973a120..00000000 --- a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/HttpUtilsTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * ============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 - * - * 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. - * ============LICENSE_END======================================================================== - */ - -package org.onap.dcaegen2.collectors.datafile.service; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import org.junit.jupiter.api.Test; - -class HttpUtilsTest { - - @Test - public void shouldReturnSuccessfulResponse() { - assertTrue(HttpUtils.isSuccessfulResponseCode(200)); - } - - @Test - public void shouldReturnBadResponse() { - assertFalse(HttpUtils.isSuccessfulResponseCode(404)); - } -}
\ No newline at end of file diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/producer/DmaapProducerHttpClientTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/producer/DmaapProducerHttpClientTest.java deleted file mode 100644 index 92a14997..00000000 --- a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/service/producer/DmaapProducerHttpClientTest.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * ============LICENSE_START====================================================================== - * Copyright (C) 2018 NOKIA Intellectual Property, 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 - * - * 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. - * ============LICENSE_END======================================================================== - */ - -package org.onap.dcaegen2.collectors.datafile.service.producer; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -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 java.net.URI; -import java.nio.charset.StandardCharsets; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.time.Duration; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Future; - -import javax.net.ssl.SSLContext; - -import org.apache.commons.codec.binary.Base64; -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.conn.ssl.NoopHostnameVerifier; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.onap.dcaegen2.collectors.datafile.exceptions.DatafileTaskException; -import org.onap.dcaegen2.collectors.datafile.http.IHttpAsyncClientBuilder; -import org.onap.dcaegen2.collectors.datafile.web.PublishRedirectStrategy; -import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.config.DmaapPublisherConfiguration; - -/** - * @author <a href="mailto:przemyslaw.wasala@nokia.com">Przemysław Wąsala</a> on 7/4/18 - * @author <a href="mailto:henrik.b.andersson@est.tech">Henrik Andersson</a> - */ -class DmaapProducerHttpClientTest { - - private static final String HOST = "54.45.33.2"; - private static final String HTTPS_SCHEME = "https"; - private static final int PORT = 1234; - private static final String USER_NAME = "dradmin"; - private static final Duration TWO_SECOND_TIMEOUT = Duration.ofSeconds(2); - - private static final Map<String, String> CONTEXT_MAP = new HashMap<>(); - - - private DmaapProducerHttpClient producerClientUnderTestSpy; - - private DmaapPublisherConfiguration dmaapPublisherConfigurationMock = mock(DmaapPublisherConfiguration.class); - - private IHttpAsyncClientBuilder clientBuilderMock; - - private CloseableHttpAsyncClient clientMock; - @SuppressWarnings("unchecked") - private Future<HttpResponse> futureMock = mock(Future.class); - - @BeforeEach - void setUp() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException { - when(dmaapPublisherConfigurationMock.dmaapHostName()).thenReturn(HOST); - when(dmaapPublisherConfigurationMock.dmaapProtocol()).thenReturn(HTTPS_SCHEME); - when(dmaapPublisherConfigurationMock.dmaapPortNumber()).thenReturn(PORT); - when(dmaapPublisherConfigurationMock.dmaapUserName()).thenReturn("dradmin"); - when(dmaapPublisherConfigurationMock.dmaapUserPassword()).thenReturn("dradmin"); - - producerClientUnderTestSpy = spy(new DmaapProducerHttpClient(dmaapPublisherConfigurationMock)); - - clientBuilderMock = mock(IHttpAsyncClientBuilder.class); - clientMock = mock(CloseableHttpAsyncClient.class); - } - - @Test - void getHttpResponseWithRederict_Success() throws Exception { - doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder(); - when(clientBuilderMock.setSSLContext(any(SSLContext.class))).thenReturn(clientBuilderMock); - when(clientBuilderMock.setSSLHostnameVerifier(any(NoopHostnameVerifier.class))).thenReturn(clientBuilderMock); - when(clientBuilderMock.build()).thenReturn(clientMock); - when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock); - HttpResponse responseMock = mock(HttpResponse.class); - when(futureMock.get()).thenReturn(responseMock); - - HttpGet request = new HttpGet(); - producerClientUnderTestSpy.getDmaapProducerResponseWithRedirect(request, CONTEXT_MAP); - - verify(clientBuilderMock).setSSLContext(any(SSLContext.class)); - verify(clientBuilderMock).setSSLHostnameVerifier(any(NoopHostnameVerifier.class)); - verify(clientBuilderMock).setRedirectStrategy(PublishRedirectStrategy.INSTANCE); - verify(clientBuilderMock).setDefaultRequestConfig(any()); - verify(clientBuilderMock).build(); - verifyNoMoreInteractions(clientBuilderMock); - - verify(clientMock).start(); - verify(clientMock).close(); - - verify(futureMock).get(); - verifyNoMoreInteractions(futureMock); - } - - @Test - void getHttpResponseWithCustomTimeout_Success() throws Exception { - doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder(); - when(clientBuilderMock.setSSLContext(any(SSLContext.class))).thenReturn(clientBuilderMock); - when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock); - when(clientBuilderMock.build()).thenReturn(clientMock); - when(clientMock.execute(any(HttpUriRequest.class), any())).thenReturn(futureMock); - HttpResponse responseMock = mock(HttpResponse.class); - when(futureMock.get()).thenReturn(responseMock); - - HttpGet request = new HttpGet(); - producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT, CONTEXT_MAP); - - ArgumentCaptor<RequestConfig> requestConfigCaptor = ArgumentCaptor.forClass(RequestConfig.class); - verify(clientBuilderMock).setSSLContext(any(SSLContext.class)); - verify(clientBuilderMock).setSSLHostnameVerifier(any(NoopHostnameVerifier.class)); - verify(clientBuilderMock).setDefaultRequestConfig(requestConfigCaptor.capture()); - RequestConfig requestConfig = requestConfigCaptor.getValue(); - assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getSocketTimeout()); - assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectTimeout()); - assertEquals(TWO_SECOND_TIMEOUT.toMillis(), requestConfig.getConnectionRequestTimeout()); - verify(clientBuilderMock).build(); - verifyNoMoreInteractions(clientBuilderMock); - - verify(clientMock).start(); - verify(clientMock).close(); - - verify(futureMock).get(); - verifyNoMoreInteractions(futureMock); - } - - @Test - public void getResponseWithException_throwsException() throws Exception { - doReturn(clientBuilderMock).when(producerClientUnderTestSpy).getHttpClientBuilder(); - when(clientBuilderMock.setDefaultRequestConfig(any(RequestConfig.class))).thenReturn(clientBuilderMock); - when(clientBuilderMock.setSSLContext(any(SSLContext.class))).thenReturn(clientBuilderMock); - when(clientBuilderMock.build()).thenReturn(clientMock); - HttpPut request = new HttpPut(); - when(clientMock.execute(any(HttpPut.class), any())).thenReturn(futureMock); - - try { - when(futureMock.get()).thenThrow(new InterruptedException("Interrupted")); - - producerClientUnderTestSpy.getDmaapProducerResponseWithCustomTimeout(request, TWO_SECOND_TIMEOUT, - CONTEXT_MAP); - - fail("Should have got an exception."); - } catch (DatafileTaskException e) { - assertTrue(e.getCause() instanceof InterruptedException); - assertEquals("Interrupted", e.getCause().getMessage()); - } catch (Exception e) { - fail("Wrong exception"); - } - - verify(clientMock).start(); - verify(clientMock).close(); - } - - @Test - public void addCredentialsToHead_success() { - HttpPut request = new HttpPut(); - - producerClientUnderTestSpy.addUserCredentialsToHead(request); - - String plainCreds = USER_NAME + ":" + USER_NAME; - byte[] plainCredsBytes = plainCreds.getBytes(StandardCharsets.ISO_8859_1); - byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); - String base64Creds = "Basic " + new String(base64CredsBytes); - Header[] authorizationHeaders = request.getHeaders("Authorization"); - assertEquals(base64Creds, authorizationHeaders[0].getValue()); - } - - @Test - public void getBaseUri_success() { - URI uri = producerClientUnderTestSpy.getBaseUri().build(); - assertEquals(HTTPS_SCHEME + "://" + HOST + ":" + PORT, uri.toString()); - } -} diff --git a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/web/PublishRedirectStrategyTest.java b/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/web/PublishRedirectStrategyTest.java deleted file mode 100644 index 0ed3c72e..00000000 --- a/datafile-dmaap-client/src/test/java/org/onap/dcaegen2/collectors/datafile/web/PublishRedirectStrategyTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * ============LICENSE_START====================================================================== - * Copyright (C) 2018 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 - * - * 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. - * ============LICENSE_END======================================================================== - */ - -package org.onap.dcaegen2.collectors.datafile.web; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolException; -import org.apache.http.RequestLine; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.protocol.HttpContext; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -class PublishRedirectStrategyTest { - - private static final String URI = "sftp://localhost:80/"; - - private static PublishRedirectStrategy publishRedirectStrategy; - - - @BeforeAll - static void setUp() { - publishRedirectStrategy = new PublishRedirectStrategy(); - } - - @Test - void isRedirectable_shouldReturnTrue() { - Assertions.assertTrue(publishRedirectStrategy.isRedirectable("Put")); - } - - @Test - void isRedirectable_shouldReturnFalse() { - Assertions.assertFalse(publishRedirectStrategy.isRedirectable("not valid method")); - } - - @Test - void getRedirect_shouldReturnCorrectUri() throws ProtocolException { - HttpRequest requestMock = mock(HttpRequest.class); - HttpResponse responseMock = mock(HttpResponse.class); - HttpContext contextMock = mock(HttpContext.class); - Header headerMock = mock(Header.class); - when(responseMock.getFirstHeader("location")).thenReturn(headerMock); - when(headerMock.getValue()).thenReturn(URI); - RequestConfig requestConfigMock = mock(RequestConfig.class); - when(contextMock.getAttribute(HttpClientContext.REQUEST_CONFIG)).thenReturn(requestConfigMock); - RequestLine requestLineMock = mock(RequestLine.class); - when(requestMock.getRequestLine()).thenReturn(requestLineMock); - when(requestLineMock.getUri()).thenReturn(URI); - - HttpUriRequest actualRedirect = publishRedirectStrategy.getRedirect(requestMock, responseMock, contextMock); - assertEquals(URI, actualRedirect.getURI().toString()); - } -} |