diff options
Diffstat (limited to 'sdc-distribution-client/src/test/java')
10 files changed, 674 insertions, 961 deletions
diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/api/asdc/RegistrationRequestTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/api/asdc/RegistrationRequestTest.java deleted file mode 100644 index 304cb56..0000000 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/api/asdc/RegistrationRequestTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2019 Nokia. 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.sdc.api.asdc; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import java.util.Collections; -import java.util.List; -import org.junit.jupiter.api.Test; - -class RegistrationRequestTest { - - private static final List<String> DIST_ENV_END_POINTS = Collections.emptyList(); - private static final boolean IS_CONSUMER_TO_SDC_DISTR_STATUS_TOPIC = true; - private static final String ENV_NAME = "ENV_NAME"; - private static final String API_KEY = "API_KEY"; - - @Test - void testConstructorShouldSetProperties() { - RegistrationRequest registrationRequest = - new RegistrationRequest(API_KEY, ENV_NAME, IS_CONSUMER_TO_SDC_DISTR_STATUS_TOPIC, DIST_ENV_END_POINTS); - assertEquals(API_KEY, registrationRequest.getApiPublicKey()); - assertEquals(DIST_ENV_END_POINTS, registrationRequest.getDistEnvEndPoints()); - assertEquals(ENV_NAME, registrationRequest.getDistrEnvName()); - assertTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic()); - } -} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientResponseTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientResponseTest.java index 8a912d9..4ff01c5 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientResponseTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientResponseTest.java @@ -33,8 +33,7 @@ import org.junit.jupiter.params.provider.MethodSource; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) -class HttpAsdcClientResponseTest { - +class HttpSdcClientResponseTest { public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {HttpStatus.SC_INTERNAL_SERVER_ERROR, "failed to send request"}, @@ -47,14 +46,14 @@ class HttpAsdcClientResponseTest { @MethodSource("data") void shouldCreateHttpResponse(int httpStatusCode, String httpMessage) throws IOException { // when - final HttpAsdcResponse response = HttpAsdcClient.createHttpResponse(httpStatusCode, httpMessage); + final HttpSdcResponse response = HttpSdcClient.createHttpResponse(httpStatusCode, httpMessage); // then assertEquals(httpStatusCode, response.getStatus()); assertEquals(httpMessage, getResponseMessage(response)); } - private String getResponseMessage(HttpAsdcResponse response) throws IOException { + private String getResponseMessage(HttpSdcResponse response) throws IOException { return IOUtils.toString(response.getMessage().getContent(), StandardCharsets.UTF_8); } -} + } diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientTest.java index 2dcfd5d..cbd12c3 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpAsdcClientTest.java @@ -43,8 +43,7 @@ import org.onap.sdc.utils.Pair; import org.onap.sdc.utils.TestConfiguration; @ExtendWith(MockitoExtension.class) -class HttpAsdcClientTest { - +class HttpSdcClientTest { private static final String URL = "http://127.0.0.1:8080/target"; private static final int HTTP_OK = 200; private static final String K_1 = "k1"; @@ -71,14 +70,14 @@ class HttpAsdcClientTest { final HttpRequestFactory httpRequestFactory = new HttpRequestFactory( configuration.getUser(), configuration.getPassword()); - final HttpAsdcClient httpAsdcClient = new HttpAsdcClient( - configuration.getAsdcAddress(), + final HttpSdcClient httpSdcClient = new HttpSdcClient( + configuration.getSdcAddress(), new HttpClientFactory(configuration), httpRequestFactory); // then - assertNotNull(httpAsdcClient); - assertEquals(HttpClientFactory.HTTP, httpAsdcClient.getHttpSchema()); + assertNotNull(httpSdcClient); + assertEquals(HttpClientFactory.HTTP, httpSdcClient.getHttpSchema()); } @Test @@ -91,25 +90,25 @@ class HttpAsdcClientTest { final HttpRequestFactory httpRequestFactory = new HttpRequestFactory( configuration.getUser(), configuration.getPassword()); - final HttpAsdcClient httpAsdcClient = new HttpAsdcClient( - configuration.getAsdcAddress(), + final HttpSdcClient httpSdcClient = new HttpSdcClient( + configuration.getSdcAddress(), new HttpClientFactory(configuration), httpRequestFactory); // then - assertNotNull(httpAsdcClient); - assertEquals(HttpClientFactory.HTTPS, httpAsdcClient.getHttpSchema()); + assertNotNull(httpSdcClient); + assertEquals(HttpClientFactory.HTTPS, httpSdcClient.getHttpSchema()); } @Test void shouldSendGetRequestWithoutAnyError() throws IOException { // given TestConfiguration configuration = givenHttpConfiguration(); - final HttpAsdcClient httpAsdcClient = createTestObj(HttpClientFactory.HTTP, configuration, httpClient); + final HttpSdcClient httpSdcClient = createTestObj(HttpClientFactory.HTTP, configuration, httpClient); CloseableHttpResponse httpResponse = givenHttpResponse(true); // when - final HttpAsdcResponse response = httpAsdcClient.getRequest(URL, HEADERS_MAP); + final HttpSdcResponse response = httpSdcClient.getRequest(URL, HEADERS_MAP); // then assertThat(response).isNotNull(); @@ -127,11 +126,11 @@ class HttpAsdcClientTest { void shouldSendPostRequestWithoutAnyError() throws IOException { // given TestConfiguration configuration = givenHttpConfiguration(); - final HttpAsdcClient httpAsdcClient = createTestObj(HttpClientFactory.HTTP, configuration, httpClient); + final HttpSdcClient httpSdcClient = createTestObj(HttpClientFactory.HTTP, configuration, httpClient); CloseableHttpResponse httpResponse = givenHttpResponse(false); // when - final HttpAsdcResponse response = httpAsdcClient.postRequest(URL, httpEntity, HEADERS_MAP); + final HttpSdcResponse response = httpSdcClient.postRequest(URL,httpEntity, HEADERS_MAP); // then assertThat(response).isNotNull(); @@ -141,17 +140,17 @@ class HttpAsdcClientTest { } - private HttpAsdcClient createTestObj(String httpProtocol, TestConfiguration configuration, CloseableHttpClient httpClient) { + private HttpSdcClient createTestObj(String httpProtocol, TestConfiguration configuration, CloseableHttpClient httpClient) { final HttpRequestFactory httpRequestFactory = new HttpRequestFactory( configuration.getUser(), configuration.getPassword()); HttpClientFactory httpClientFactory = mock(HttpClientFactory.class); when(httpClientFactory.createInstance()).thenReturn(new Pair<>(httpProtocol, httpClient)); - final HttpAsdcClient httpAsdcClient = new HttpAsdcClient( - configuration.getAsdcAddress(), + final HttpSdcClient httpSdcClient = new HttpSdcClient( + configuration.getSdcAddress(), httpClientFactory, httpRequestFactory); - return httpAsdcClient; + return httpSdcClient; } private CloseableHttpResponse givenHttpResponse(HttpEntity httpEntity, Header[] headers, boolean includeGetAllHeaders) { diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpClientFactoryTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpClientFactoryTest.java index 347b7f5..2292fc4 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpClientFactoryTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpClientFactoryTest.java @@ -41,7 +41,7 @@ class HttpClientFactoryTest { TestConfiguration config = spy(new TestConfiguration()); HttpClientFactory httpClientFactory = new HttpClientFactory(config); when(config.activateServerTLSAuth()).thenReturn(true); - when(config.getKeyStorePath()).thenReturn("src/test/resources/asdc-client.jks"); + when(config.getKeyStorePath()).thenReturn("src/test/resources/sdc-client.jks"); when(config.getKeyStorePassword()).thenReturn("Aa123456"); Pair<String, CloseableHttpClient> client = httpClientFactory.createInstance(); SSLConnectionSocketFactory sslsf = spy(SSLConnectionSocketFactory.getSocketFactory()); @@ -74,13 +74,13 @@ class HttpClientFactoryTest { } @Test - void shouldReturnSSLConnectionError() throws HttpAsdcClientException { + void shouldReturnSSLConnectionError() throws HttpSdcClientException{ TestConfiguration config = spy(new TestConfiguration()); HttpClientFactory httpClientFactory = new HttpClientFactory(config); when(config.activateServerTLSAuth()).thenReturn(true); when(config.getKeyStorePath()).thenReturn("src/test/resources/dummy.jks"); when(config.getKeyStorePassword()).thenReturn("Aa123456"); - assertThrows(HttpAsdcClientException.class, () -> httpClientFactory.createInstance()); + assertThrows(HttpSdcClientException.class, () -> httpClientFactory.createInstance()); } } diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java index b09de78..61b8388 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/http/SdcConnectorClientTest.java @@ -22,20 +22,14 @@ package org.onap.sdc.http; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; +import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; 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 com.att.nsa.apiClient.credentials.ApiCredential; import com.google.common.hash.Hashing; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -43,199 +37,180 @@ import fj.data.Either; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Matchers; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.onap.sdc.api.asdc.RegistrationRequest; import org.onap.sdc.api.consumer.IConfiguration; import org.onap.sdc.api.notification.IArtifactInfo; import org.onap.sdc.api.results.IDistributionClientResult; -import org.onap.sdc.impl.DistributionClientResultImpl; import org.onap.sdc.utils.DistributionActionResultEnum; import org.onap.sdc.utils.Pair; +import org.onap.sdc.utils.kafka.KafkaDataResponse; -class SdcConnectorClientTest { +public class SdcConnectorClientTest { + + private static final Gson gson = new GsonBuilder().create(); + private static final HttpSdcClient httpClient = mock(HttpSdcClient.class); + private static final IConfiguration configuration = mock(IConfiguration.class); + private static final HttpSdcResponse httpSdcResponse = mock(HttpSdcResponse.class); + private static final Map<String, String> mockHeaders = new HashMap<>(); + private static SdcConnectorClient sdcClient; - private static final String MOCK_ENV = "MockEnv"; - private static final String MOCK_API_KEY = "MockApikey"; private static final String ARTIFACT_URL = "http://127.0.0.1/artifact/url"; private static final String IT_JUST_DIDN_T_WORK = "It just didn't work"; private static final List<String> ARTIFACT_TYPES = Arrays.asList("Service", "Resource", "VF", "VFC"); - private static final int PORT = 49512; - private static final byte[] BYTES = new byte[]{0xA, 0xB, 0xC, 0xD}; - private static Gson gson = new GsonBuilder().create(); private static final String VALID_JSON_PAYLOAD = gson.toJson(ARTIFACT_TYPES); - private static HttpAsdcClient httpClient = mock(HttpAsdcClient.class); - private static IConfiguration configuration = mock(IConfiguration.class); - private static ApiCredential apiCredential = mock(ApiCredential.class); - private static HttpAsdcResponse httpAsdcResponse = mock(HttpAsdcResponse.class); - @SuppressWarnings("unchecked") - private static Either<TopicRegistrationResponse, DistributionClientResultImpl> mockResponse = - Mockito.mock(Either.class); - private static Map<String, String> mockHeaders = new HashMap<>(); - private static SdcConnectorClient asdcClient; - Pair<HttpAsdcResponse, CloseableHttpResponse> mockPair = new Pair<>(httpAsdcResponse, null); - private HttpEntity lastHttpEntity = null; + private static final String KAFKA_DATA = "{\"kafkaBootStrapServer\": \"onap-strimzi-kafka-bootstrap:9092\",\"distrNotificationTopicName\": \"SDC-DISTR-NOTIF-TOPIC-AUTO\",\"distrStatusTopicName\": \"SDC-DISTR-STATUS-TOPIC-AUTO\"}"; + private static final String VALID_KAFKA_JSON_PAYLOAD = gson.toJson(KAFKA_DATA); + private static final int PORT = 49512; + private static final byte[] BYTES = new byte[] {0xA, 0xB, 0xC, 0xD}; @BeforeAll public static void beforeClass() { - asdcClient = Mockito.spy(new SdcConnectorClient(configuration, httpClient)); - when(apiCredential.getApiKey()).thenReturn(MOCK_API_KEY); - when(httpAsdcResponse.getStatus()).thenReturn(HttpStatus.SC_OK); + sdcClient = Mockito.spy(new SdcConnectorClient(configuration, httpClient)); + when(httpSdcResponse.getStatus()).thenReturn(HttpStatus.SC_OK); - doReturn(mockHeaders).when(asdcClient).addHeadersToHttpRequest(Mockito.anyString()); - doReturn(mockResponse).when(asdcClient).parseRegistrationResponse(httpAsdcResponse); - } - - @BeforeEach - public void beforeMethod() { - Mockito.reset(configuration, httpClient); - lastHttpEntity = null; - when(configuration.getEnvironmentName()).thenReturn(MOCK_ENV); - - doAnswer(new Answer<Pair<HttpAsdcResponse, CloseableHttpResponse>>() { - @Override - public Pair<HttpAsdcResponse, CloseableHttpResponse> answer(InvocationOnMock invocation) throws Throwable { - lastHttpEntity = invocation.getArgument(1, HttpEntity.class); - return mockPair; - } - }).when(httpClient).postRequest(eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), any(HttpEntity.class), eq(mockHeaders), eq(false)); + doReturn(mockHeaders).when(sdcClient).addHeadersToHttpRequest(Mockito.anyString()); } @Test - void initAndCloseTest() { + public void initAndCloseTest() { IConfiguration conf = Mockito.mock(IConfiguration.class); when(conf.getUser()).thenReturn("user"); when(conf.getPassword()).thenReturn("password"); when(conf.isUseHttpsWithSDC()).thenReturn(true); when(conf.activateServerTLSAuth()).thenReturn(false); - final HttpAsdcClient httpClient = new HttpAsdcClient(conf); + final HttpSdcClient httpClient = new HttpSdcClient(conf); SdcConnectorClient client = new SdcConnectorClient(conf, httpClient); client.close(); - - assertThrows(IllegalStateException.class, () -> { - //check if client is really closed - httpClient.getRequest(AsdcUrls.POST_FOR_TOPIC_REGISTRATION, new HashMap<>()); - }); - } @Test - void testConsumeProduceStatusTopicFalse() throws UnsupportedOperationException, IOException { - testConsumeProduceStatusTopic(false); + void getValidKafkaDataHappyScenarioTest() throws IOException { + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); + CloseableHttpResponse closeableHttpResponseMock = mock(CloseableHttpResponse.class); + HttpEntity messageMock = mock(HttpEntity.class); + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = + new Pair<>(responseMock, closeableHttpResponseMock); + + when(responseMock.getStatus()).thenReturn(HttpStatus.SC_OK); + when(responseMock.getMessage()).thenReturn(messageMock); + when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(KAFKA_DATA.getBytes())); + when(httpClient.getRequest(eq(SdcUrls.GET_KAFKA_DIST_DATA), Matchers.any(), eq(false))) + .thenReturn(responsePair); + + Either<KafkaDataResponse, IDistributionClientResult> result = sdcClient.getKafkaDistData(); + assertTrue(result.isLeft()); + KafkaDataResponse kafkaDataResponse = result.left().value(); + assertEquals("SDC-DISTR-NOTIF-TOPIC-AUTO", kafkaDataResponse.getDistrNotificationTopicName()); } @Test - void testConsumeProduceStatusTopicTrue() throws UnsupportedOperationException, IOException { - testConsumeProduceStatusTopic(true); - } + void getValidKafkaDataErrorResponseScenarioTest() throws IOException { + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); + HttpEntity messageMock = mock(HttpEntity.class); + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); + + when(responseMock.getStatus()).thenReturn(HttpStatus.SC_GATEWAY_TIMEOUT); + when(responseMock.getMessage()).thenReturn(messageMock); + when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(IT_JUST_DIDN_T_WORK.getBytes())); + when(httpClient.getRequest(eq(SdcUrls.GET_KAFKA_DIST_DATA), Matchers.any(), eq(false))) + .thenReturn(responsePair); - private void testConsumeProduceStatusTopic(final boolean isConsumeProduceStatusFlag) throws IOException { - when(configuration.isConsumeProduceStatusTopic()).thenReturn(isConsumeProduceStatusFlag); - asdcClient.registerAsdcTopics(apiCredential); - verify(httpClient, times(1)).postRequest(eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), any(HttpEntity.class), eq(mockHeaders), eq(false)); - assertNotNull(lastHttpEntity); - RegistrationRequest actualRegRequest - = gson.fromJson(IOUtils.toString(lastHttpEntity.getContent(), StandardCharsets.UTF_8), RegistrationRequest.class); - RegistrationRequest expectedRegRequest - = gson.fromJson(excpectedStringBody(isConsumeProduceStatusFlag), RegistrationRequest.class); - - assertEquals(expectedRegRequest.getApiPublicKey(), actualRegRequest.getApiPublicKey()); - assertEquals(expectedRegRequest.getDistrEnvName(), actualRegRequest.getDistrEnvName()); - assertEquals(expectedRegRequest.getIsConsumerToSdcDistrStatusTopic(), actualRegRequest.getIsConsumerToSdcDistrStatusTopic()); + Either<KafkaDataResponse, IDistributionClientResult> result = sdcClient.getKafkaDistData(); + assertTrue(result.isRight()); + IDistributionClientResult distributionClientResult = result.right().value(); + assertEquals(DistributionActionResultEnum.SDC_SERVER_TIMEOUT, + distributionClientResult.getDistributionActionResult()); } @Test - void getValidArtifactTypesListHappyScenarioTest() throws IOException { - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + public void getValidArtifactTypesListHappyScenarioTest() throws IOException { + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); CloseableHttpResponse closeableHttpResponseMock = mock(CloseableHttpResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, closeableHttpResponseMock); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_OK); when(responseMock.getMessage()).thenReturn(messageMock); when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(VALID_JSON_PAYLOAD.getBytes())); - when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + when(httpClient.getRequest(eq(SdcUrls.GET_VALID_ARTIFACT_TYPES), Matchers.any(), eq(false))) .thenReturn(responsePair); - Either<List<String>, IDistributionClientResult> result = asdcClient.getValidArtifactTypesList(); + Either<List<String>, IDistributionClientResult> result = sdcClient.getValidArtifactTypesList(); assertTrue(result.isLeft()); List<String> list = result.left().value(); assertEquals(ARTIFACT_TYPES, list); } @Test - void getValidArtifactTypesListErrorResponseScenarioTest() throws IOException { - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + public void getValidArtifactTypesListErrorResponseScenarioTest() throws IOException { + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_GATEWAY_TIMEOUT); when(responseMock.getMessage()).thenReturn(messageMock); when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(IT_JUST_DIDN_T_WORK.getBytes())); - when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + when(httpClient.getRequest(eq(SdcUrls.GET_VALID_ARTIFACT_TYPES), Matchers.any(), eq(false))) .thenReturn(responsePair); - Either<List<String>, IDistributionClientResult> result = asdcClient.getValidArtifactTypesList(); + Either<List<String>, IDistributionClientResult> result = sdcClient.getValidArtifactTypesList(); assertTrue(result.isRight()); IDistributionClientResult distributionClientResult = result.right().value(); - assertEquals(DistributionActionResultEnum.ASDC_SERVER_TIMEOUT, + assertEquals(DistributionActionResultEnum.SDC_SERVER_TIMEOUT, distributionClientResult.getDistributionActionResult()); } @Test - void getValidArtifactTypesListExceptionDuringConnectionClosingTest() throws IOException { - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + public void getValidArtifactTypesListExceptionDuringConnectionClosingTest() throws IOException { + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); CloseableHttpResponse closeableHttpResponseMock = mock(CloseableHttpResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, closeableHttpResponseMock); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_GATEWAY_TIMEOUT); when(responseMock.getMessage()).thenReturn(messageMock); when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(VALID_JSON_PAYLOAD.getBytes())); - when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + when(httpClient.getRequest(eq(SdcUrls.GET_VALID_ARTIFACT_TYPES), Matchers.any(), eq(false))) .thenReturn(responsePair); doThrow(new IOException("Test exception")).when(closeableHttpResponseMock).close(); - Either<List<String>, IDistributionClientResult> result = asdcClient.getValidArtifactTypesList(); + Either<List<String>, IDistributionClientResult> result = sdcClient.getValidArtifactTypesList(); assertTrue(result.isRight()); IDistributionClientResult distributionClientResult = result.right().value(); - assertEquals(DistributionActionResultEnum.ASDC_SERVER_TIMEOUT, + assertEquals(DistributionActionResultEnum.SDC_SERVER_TIMEOUT, distributionClientResult.getDistributionActionResult()); } @Test - void getValidArtifactTypesListParsingExceptionHandlingTest() throws IOException { - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + public void getValidArtifactTypesListParsingExceptionHandlingTest() throws IOException { + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); CloseableHttpResponse closeableHttpResponseMock = mock(CloseableHttpResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, closeableHttpResponseMock); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_OK); when(responseMock.getMessage()).thenReturn(messageMock); when(messageMock.getContent()).thenReturn(new ThrowingInputStreamForTesting()); - when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + when(httpClient.getRequest(eq(SdcUrls.GET_VALID_ARTIFACT_TYPES), Matchers.any(), eq(false))) .thenReturn(responsePair); - Either<List<String>, IDistributionClientResult> result = asdcClient.getValidArtifactTypesList(); + Either<List<String>, IDistributionClientResult> result = sdcClient.getValidArtifactTypesList(); assertTrue(result.isRight()); IDistributionClientResult distributionClientResult = result.right().value(); assertEquals(DistributionActionResultEnum.GENERAL_ERROR, @@ -243,59 +218,17 @@ class SdcConnectorClientTest { } @Test - void unregisterTopicsErrorDuringProcessingTest() throws IOException { - when(configuration.getAsdcAddress()).thenReturn("127.0.0.1" + PORT); - when(configuration.isConsumeProduceStatusTopic()).thenReturn(false); - when(configuration.getMsgBusAddress()) - .thenReturn(Arrays.asList("http://127.0.0.1:45321/dmaap", "http://127.0.0.1:45321/dmaap")); - - String failMessage = "It just didn't work"; - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); - HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); - - when(responseMock.getStatus()).thenReturn(HttpStatus.SC_BAD_GATEWAY); - when(responseMock.getMessage()).thenReturn(messageMock); - when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(failMessage.getBytes())); - doReturn(responsePair).when(httpClient) - .postRequest(eq(AsdcUrls.POST_FOR_UNREGISTER), any(HttpEntity.class), any(), eq(false)); - - IDistributionClientResult result = asdcClient.unregisterTopics(apiCredential); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, result.getDistributionActionResult()); - } - - @Test - void unregisterTopicsHappyScenarioTest() throws IOException { - when(configuration.getAsdcAddress()).thenReturn("127.0.0.1" + PORT); - when(configuration.isConsumeProduceStatusTopic()).thenReturn(false); - - String failMessage = ""; - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); - HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); - - when(responseMock.getStatus()).thenReturn(HttpStatus.SC_NO_CONTENT); - when(responseMock.getMessage()).thenReturn(messageMock); - when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(failMessage.getBytes())); - doReturn(responsePair).when(httpClient) - .postRequest(eq(AsdcUrls.POST_FOR_UNREGISTER), any(HttpEntity.class), any(), eq(false)); - - IDistributionClientResult result = asdcClient.unregisterTopics(apiCredential); - assertEquals(DistributionActionResultEnum.SUCCESS, result.getDistributionActionResult()); - } - - @Test - void downloadArtifactHappyScenarioTest() throws IOException { + public void downloadArtifactHappyScenarioTest() throws IOException { Map<String, String> headers = new HashMap<>(); - headers.put(asdcClient.CONTENT_DISPOSITION_HEADER, "SomeHeader"); + headers.put(SdcConnectorClient.CONTENT_DISPOSITION_HEADER, "SomeHeader"); IArtifactInfo artifactInfo = mock(IArtifactInfo.class); when(artifactInfo.getArtifactURL()).thenReturn(ARTIFACT_URL); when(artifactInfo.getArtifactChecksum()).thenReturn(Hashing.md5().hashBytes(BYTES).toString()); - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_OK); when(responseMock.getMessage()).thenReturn(messageMock); @@ -303,70 +236,62 @@ class SdcConnectorClientTest { when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(BYTES)); doReturn(responsePair).when(httpClient).getRequest(eq(ARTIFACT_URL), any(), eq(false)); - IDistributionClientResult result = asdcClient.downloadArtifact(artifactInfo); + IDistributionClientResult result = sdcClient.downloadArtifact(artifactInfo); assertEquals(DistributionActionResultEnum.SUCCESS, result.getDistributionActionResult()); } @Test - void downloadArtifactDataIntegrityProblemTest() throws IOException { + public void downloadArtifactDataIntegrityProblemTest() throws IOException { IArtifactInfo artifactInfo = mock(IArtifactInfo.class); when(artifactInfo.getArtifactURL()).thenReturn(ARTIFACT_URL); - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_OK); when(responseMock.getMessage()).thenReturn(messageMock); when(messageMock.getContent()).thenReturn(new ByteArrayInputStream(BYTES)); doReturn(responsePair).when(httpClient).getRequest(eq(ARTIFACT_URL), any(), eq(false)); - IDistributionClientResult result = asdcClient.downloadArtifact(artifactInfo); + IDistributionClientResult result = sdcClient.downloadArtifact(artifactInfo); assertEquals(DistributionActionResultEnum.DATA_INTEGRITY_PROBLEM, result.getDistributionActionResult()); } @Test - void downloadArtifactExceptionDuringDownloadHandlingTest() throws IOException { + public void downloadArtifactExceptionDuringDownloadHandlingTest() throws IOException { IArtifactInfo artifactInfo = mock(IArtifactInfo.class); when(artifactInfo.getArtifactURL()).thenReturn(ARTIFACT_URL); - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_OK); when(responseMock.getMessage()).thenReturn(messageMock); when(messageMock.getContent()).thenReturn(new ThrowingInputStreamForTesting()); doReturn(responsePair).when(httpClient).getRequest(eq(ARTIFACT_URL), any(), eq(false)); - IDistributionClientResult result = asdcClient.downloadArtifact(artifactInfo); + IDistributionClientResult result = sdcClient.downloadArtifact(artifactInfo); assertEquals(DistributionActionResultEnum.GENERAL_ERROR, result.getDistributionActionResult()); } @Test - void downloadArtifactHandleDownloadErrorTest() throws IOException { + public void downloadArtifactHandleDownloadErrorTest() throws IOException { IArtifactInfo artifactInfo = mock(IArtifactInfo.class); when(artifactInfo.getArtifactURL()).thenReturn(ARTIFACT_URL); - HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); + HttpSdcResponse responseMock = mock(HttpSdcResponse.class); HttpEntity messageMock = mock(HttpEntity.class); - Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); + Pair<HttpSdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); when(responseMock.getStatus()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); when(responseMock.getMessage()).thenReturn(messageMock); when(messageMock.getContent()).thenReturn(new ThrowingInputStreamForTesting()); doReturn(responsePair).when(httpClient).getRequest(eq(ARTIFACT_URL), any(), eq(false)); - IDistributionClientResult result = asdcClient.downloadArtifact(artifactInfo); - assertEquals(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, result.getDistributionActionResult()); - } - - private String excpectedStringBody(boolean isConsumeProduceStatusTopic) { - String stringBodyTemplate = - "{\r\n" + " \"apiPublicKey\": \"MockApikey\",\r\n" + " \"distrEnvName\": \"MockEnv\",\r\n" - + " \"isConsumerToSdcDistrStatusTopic\": %s\r\n" + "}"; - return String.format(stringBodyTemplate, isConsumeProduceStatusTopic); - + IDistributionClientResult result = sdcClient.downloadArtifact(artifactInfo); + assertEquals(DistributionActionResultEnum.SDC_SERVER_PROBLEM, result.getDistributionActionResult()); } static class ThrowingInputStreamForTesting extends InputStream { @@ -376,4 +301,4 @@ class SdcConnectorClientTest { throw new IOException("Not implemented. This is expected as the implementation is for unit tests only."); } } -} +}
\ No newline at end of file diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java index 0297918..7354c6c 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientTest.java @@ -22,29 +22,29 @@ package org.onap.sdc.impl; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.att.nsa.apiClient.http.HttpException; -import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; -import com.att.nsa.cambria.client.CambriaIdentityManager; import fj.data.Either; import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Assertions; +import org.junitpioneer.jupiter.SetEnvironmentVariable; import org.mockito.Mockito; import org.onap.sdc.api.IDistributionClient; import org.onap.sdc.api.consumer.IConfiguration; import org.onap.sdc.api.notification.IArtifactInfo; import org.onap.sdc.api.notification.IVfModuleMetadata; import org.onap.sdc.api.results.IDistributionClientResult; -import org.onap.sdc.http.HttpAsdcClient; +import org.onap.sdc.http.HttpSdcClient; import org.onap.sdc.http.SdcConnectorClient; -import org.onap.sdc.http.TopicRegistrationResponse; import org.onap.sdc.utils.ArtifactTypeEnum; import org.onap.sdc.utils.ArtifactsUtils; import org.onap.sdc.utils.DistributionActionResultEnum; @@ -52,13 +52,14 @@ import org.onap.sdc.utils.Pair; import org.onap.sdc.utils.TestConfiguration; import org.onap.sdc.utils.TestNotificationCallback; import org.onap.sdc.utils.Wrapper; +import org.onap.sdc.utils.kafka.KafkaDataResponse; +import org.onap.sdc.utils.kafka.SdcKafkaConsumer; class DistributionClientTest { - - static CambriaIdentityManager cc; DistributionClientImpl client = Mockito.spy(new DistributionClientImpl()); IConfiguration testConfiguration = new TestConfiguration(); SdcConnectorClient connector = Mockito.mock(SdcConnectorClient.class); + SdcKafkaConsumer consumer = mock(SdcKafkaConsumer.class); @AfterEach @@ -68,8 +69,8 @@ class DistributionClientTest { @Test void validateConfigurationTest() { - final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration( - new Wrapper<IDistributionClientResult>(), testConfiguration); + final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration( + new Wrapper<>(), testConfiguration); DistributionActionResultEnum validationResult = distributionActionResultEnumConfigurationPair.getFirst(); Configuration configuration = distributionActionResultEnumConfigurationPair.getSecond(); assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); @@ -82,7 +83,7 @@ class DistributionClientTest { TestConfiguration userConfig = new TestConfiguration(); userConfig.setPollingInterval(1); userConfig.setPollingTimeout(2); - final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration( + final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration( new Wrapper<>(), userConfig); DistributionActionResultEnum validationResult = distributionActionResultEnumConfigurationPair.getFirst(); Configuration configuration = distributionActionResultEnumConfigurationPair.getSecond(); @@ -120,23 +121,8 @@ class DistributionClientTest { } @Test - void initWithMocksBadConfigurationTest() throws HttpException, CambriaApiException, IOException { - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either<TopicRegistrationResponse, DistributionClientResultImpl> topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - reconfigureAsdcConnector(connector, client); - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))) - .thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - + public void initWithMocksBadConfigurationTest() { + reconfigureSdcConnector(connector, client); // no password TestConfiguration testPassword = new TestConfiguration(); testPassword.setPassword(null); @@ -157,19 +143,19 @@ class DistributionClientTest { validationResult = client.init(testUser, new TestNotificationCallback()); assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); - // no ASDC server fqdn + // no SDC server fqdn TestConfiguration testServerFqdn = new TestConfiguration(); - testServerFqdn.setAsdcAddress(null); + testServerFqdn.setSdcAddress(null); validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_SDC_FQDN, validationResult.getDistributionActionResult()); - testServerFqdn.setAsdcAddress(""); + testServerFqdn.setSdcAddress(""); validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_SDC_FQDN, validationResult.getDistributionActionResult()); - testServerFqdn.setAsdcAddress("this##is##bad##fqdn"); + testServerFqdn.setSdcAddress("this##is##bad##fqdn"); validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN, validationResult.getDistributionActionResult()); + assertEquals(DistributionActionResultEnum.CONF_INVALID_SDC_FQDN, validationResult.getDistributionActionResult()); // no consumerId TestConfiguration testConsumerId = new TestConfiguration(); @@ -191,93 +177,63 @@ class DistributionClientTest { validationResult = client.init(testEnv, new TestNotificationCallback()); assertEquals(DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME, validationResult.getDistributionActionResult()); - Mockito.verify(client, Mockito.times(0)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(0)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); } - private void reconfigureAsdcConnector(SdcConnectorClient connector, DistributionClientImpl client) { - doReturn(connector).when(client).createAsdcConnector(any()); + private void reconfigureSdcConnector(SdcConnectorClient connector, DistributionClientImpl client) { + doReturn(connector).when(client).createSdcConnector(any()); } @Test - void initFailedConnectAsdcTest() throws HttpException, CambriaApiException, IOException { - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))) - .thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; + public void initFailedConnectSdcTest() { - TestConfiguration badAsdcConfig = new TestConfiguration(); - if (badAsdcConfig.isUseHttpsWithSDC() == null) { + TestConfiguration badSdcConfig = new TestConfiguration(); + if (badSdcConfig.isUseHttpsWithSDC() == null) { System.out.println("null for HTTPS then TRUE"); } else { - System.out.println("isUseHttpsWithSDC set to " + badAsdcConfig.isUseHttpsWithSDC()); + System.out.println("isUseHttpsWithSDC set to " + badSdcConfig.isUseHttpsWithSDC()); } - badAsdcConfig.setAsdcAddress("badhost:8080"); + badSdcConfig.setSdcAddress("badhost:8080"); - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + IDistributionClientResult init = client.init(badSdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SDC_CONNECTION_FAILED, init.getDistributionActionResult()); - badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("localhost:8181"); + badSdcConfig = new TestConfiguration(); + badSdcConfig.setSdcAddress("localhost:8181"); - init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + init = client.init(badSdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SDC_CONNECTION_FAILED, init.getDistributionActionResult()); } @Test - void initFailedConnectAsdcInHttpTest() throws HttpException, CambriaApiException, IOException { - // cambriaMock + public void initFailedConnectSdcInHttpTest() { - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))) - .thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; + TestConfiguration badSdcConfig = new TestConfiguration(); + badSdcConfig.setSdcAddress("badhost:8080"); + badSdcConfig.setUseHttpsWithSDC(false); - TestConfiguration badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("badhost:8080"); - badAsdcConfig.setUseHttpsWithSDC(false); + IDistributionClientResult init = client.init(badSdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SDC_CONNECTION_FAILED, init.getDistributionActionResult()); - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + badSdcConfig = new TestConfiguration(); + badSdcConfig.setSdcAddress("localhost:8181"); + badSdcConfig.setUseHttpsWithSDC(false); - badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("localhost:8181"); - badAsdcConfig.setUseHttpsWithSDC(false); - - init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + init = client.init(badSdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SDC_CONNECTION_FAILED, init.getDistributionActionResult()); } @Test - void getConfigurationTest() throws HttpException, CambriaApiException, IOException { + public void getConfigurationTest() { // connectorMock mockArtifactTypeList(); - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either<TopicRegistrationResponse, DistributionClientResultImpl> topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - IDistributionClientResult success = initSuccesResult(); - Mockito.when(connector.unregisterTopics(Mockito.any(ApiCredential.class))).thenReturn(success); - - reconfigureAsdcConnector(connector, client); + mockKafkaData(); + reconfigureSdcConnector(connector, client); + TestConfiguration badSdcConfig = new TestConfiguration(); + badSdcConfig.setPollingInterval(-5); - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))) - .thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - TestConfiguration badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setPollingInterval(-5); - - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); + IDistributionClientResult init = client.init(badSdcConfig, new TestNotificationCallback()); assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); String confString = client.getConfiguration().toString(); @@ -301,32 +257,12 @@ class DistributionClientTest { } @Test - void initWithMocksTest() throws HttpException, CambriaApiException, IOException { - + public void initWithMocksTest() { mockArtifactTypeList(); - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either<TopicRegistrationResponse, DistributionClientResultImpl> topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - IDistributionClientResult success = initSuccesResult(); - Mockito.when(connector.unregisterTopics(Mockito.any(ApiCredential.class))).thenReturn(success); - - reconfigureAsdcConnector(connector, client); - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))) - .thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - + mockKafkaData(); + reconfigureSdcConnector(connector, client); IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); assertEquals(DistributionActionResultEnum.SUCCESS, initResponse.getDistributionActionResult()); - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(1)).registerAsdcTopics(Mockito.any(ApiCredential.class)); System.out.println(initResponse); } @@ -340,137 +276,31 @@ class DistributionClientTest { Mockito.when(connector.getValidArtifactTypesList()).thenReturn(eitherArtifactTypes); } - @Test - void testAlreadyInitTest() throws HttpException, CambriaApiException, IOException { - initWithMocksTest(); - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, initResponse.getDistributionActionResult()); + private void mockKafkaData() { + KafkaDataResponse kafkaData = new KafkaDataResponse(); + kafkaData.setKafkaBootStrapServer("localhost:9092"); + kafkaData.setDistrNotificationTopicName("SDC-DISTR-NOTIF-TOPIC-AUTO"); + kafkaData.setDistrStatusTopicName("SDC-DISTR-STATUS-TOPIC-AUTO"); + final Either<KafkaDataResponse, IDistributionClientResult> eitherArtifactTypes = Either.left(kafkaData); + Mockito.when(connector.getKafkaDistData()).thenReturn(eitherArtifactTypes); } @Test - void initGetServerFailedTest() throws HttpException, CambriaApiException, IOException { - - // connectorMock - IDistributionClientResult getServersResult = new DistributionClientResultImpl(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, "problem"); - Either<List<String>, IDistributionClientResult> serversResult = Either.right(getServersResult); - doReturn(serversResult).when(client).getUEBServerList(); - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either<TopicRegistrationResponse, DistributionClientResultImpl> topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - reconfigureAsdcConnector(connector, client); - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))) - .thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - + void testAlreadyInitTest() { + initWithMocksTest(); IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_SERVER_PROBLEM, initResponse.getDistributionActionResult()); - - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(0)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - - System.out.println(initResponse); - } - - @Test - void initCreateKeysFailedTest() throws HttpException, CambriaApiException, IOException { - - // connectorMock - mockArtifactTypeList(); - - TopicRegistrationResponse topics = new TopicRegistrationResponse(); - topics.setDistrNotificationTopicName("notificationTopic"); - topics.setDistrStatusTopicName("statusTopic"); - Either<TopicRegistrationResponse, DistributionClientResultImpl> topicsResult = Either.left(topics); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - reconfigureAsdcConnector(connector, client); - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))).thenThrow(new CambriaApiException("failure")); - client.cambriaIdentityManager = cambriaMock; - - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.UEB_KEYS_CREATION_FAILED, initResponse.getDistributionActionResult()); - - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(0)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - System.out.println(initResponse); - } - - @Test - void initRegistrationFailedTest() throws HttpException, CambriaApiException, IOException { - - // connectorMock - mockArtifactTypeList(); - DistributionClientResultImpl failureResult = new DistributionClientResultImpl(DistributionActionResultEnum.BAD_REQUEST, "Bad Request"); - Either<TopicRegistrationResponse, DistributionClientResultImpl> topicsResult = Either.right(failureResult); - Mockito.when(connector.registerAsdcTopics(Mockito.any(ApiCredential.class))).thenReturn(topicsResult); - - reconfigureAsdcConnector(connector, client); - - // cambriaMock - - CambriaIdentityManager cambriaMock = Mockito.mock(CambriaIdentityManager.class); - Mockito.when(cambriaMock.createApiKey(Mockito.any(String.class), Mockito.any(String.class))) - .thenReturn(new ApiCredential("public", "secret")); - client.cambriaIdentityManager = cambriaMock; - - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.BAD_REQUEST, initResponse.getDistributionActionResult()); - Mockito.verify(client, Mockito.times(1)).getUEBServerList(); - Mockito.verify(cambriaMock, Mockito.times(1)).createApiKey(Mockito.anyString(), Mockito.anyString()); - Mockito.verify(connector, Mockito.times(1)).registerAsdcTopics(Mockito.any(ApiCredential.class)); - System.out.println(initResponse); + assertEquals(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, initResponse.getDistributionActionResult()); } @Test void testStartWithoutInit() { - IDistributionClientResult result = client.start(); - assertEquals(DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED, result.getDistributionActionResult()); - } - - private IArtifactInfo initArtifactInfo() { - ArtifactInfoImpl artifactInfo = new ArtifactInfoImpl(); - artifactInfo.setArtifactURL("/sdc/v1/services/serviceName/0.1/artifacts/aaa.hh"); - artifactInfo.setArtifactChecksum(ArtifactsUtils.getValidChecksum()); - return artifactInfo; - } - - // ########### TESTS TO ADD TO CI START ########### - /*public void createKeysTestCI() throws MalformedURLException, GeneralSecurityException { - validateConfigurationTest(); - CambriaIdentityManager trueCambria = new CambriaClientBuilders.IdentityManagerBuilder().usingHttps().usingHosts(serverList).build(); - client.cambriaIdentityManager = trueCambria; - DistributionClientResultImpl keysResult = client.createUebKeys(); - assertEquals(DistributionActionResultEnum.SUCCESS, keysResult.getDistributionActionResult()); - assertFalse(client.credential.getApiKey().isEmpty()); - assertFalse(client.credential.getApiSecret().isEmpty()); - - System.out.println(keysResult); - System.out.println("keys: public=" + client.credential.getApiKey() + " | secret=" + client.credential.getApiSecret()); - } -*/ - public void initTestCI() { - IDistributionClient distributionClient = DistributionClientFactory.createDistributionClient(); - IDistributionClientResult init = distributionClient.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); - + IDistributionClientResult result = client.start(); + assertSame(DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED, + result.getDistributionActionResult()); } @Test - void testDecodeVfModuleArtifact() throws IOException { + void testDecodeVfModuleArtifact() { String vfModuleContent = getVFModuleExample(); List<IVfModuleMetadata> decodeVfModuleArtifact = client.decodeVfModuleArtifact(vfModuleContent.getBytes()); assertEquals(1, decodeVfModuleArtifact.size()); @@ -504,23 +334,4 @@ class DistributionClientTest { " }\r\n" + "]"; } - - - public void connectorRegisterCI() { - SdcConnectorClient connector = new SdcConnectorClient(testConfiguration, new HttpAsdcClient(testConfiguration)); - - ApiCredential creds = new ApiCredential("publicKey", "secretKey"); - Either<TopicRegistrationResponse, DistributionClientResultImpl> topicsFromAsdc = connector.registerAsdcTopics(creds); - assertTrue(topicsFromAsdc.isLeft()); - - } - - public void downloadArtifactTestCI() { - SdcConnectorClient connector = new SdcConnectorClient(testConfiguration, new HttpAsdcClient(testConfiguration)); - IArtifactInfo artifactInfo = initArtifactInfo(); - connector.downloadArtifact(artifactInfo); - - } - // ########### TESTS TO ADD TO CI END ########### - } diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java index 1e3db81..a70a537 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/NotificationConsumerTest.java @@ -21,30 +21,20 @@ package org.onap.sdc.impl; -import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -import com.att.nsa.cambria.client.CambriaConsumer; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import java.io.IOException; import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import org.awaitility.Durations; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -56,359 +46,297 @@ import org.onap.sdc.utils.ArtifactTypeEnum; import org.onap.sdc.utils.DistributionActionResultEnum; import org.onap.sdc.utils.DistributionClientConstants; import org.onap.sdc.utils.TestConfiguration; +import org.onap.sdc.utils.kafka.SdcKafkaConsumer; class NotificationConsumerTest { - - final static IDistributionClientResult DISTRIBUTION_SUCCESS_RESULT = buildSuccessResult(); - private final CambriaConsumer cambriaConsumer = mock(CambriaConsumer.class); - private final INotificationCallback clientCallback = spy(INotificationCallback.class); - private final Queue<Iterable<String>> notificationsQueue = new LinkedList<>(); - private final DistributionClientImpl distributionClient = Mockito.spy(DistributionClientImpl.class); - private List<String> artifactsTypes = List.of(ArtifactTypeEnum.HEAT.name()); - private final List<Boolean> notificationStatusResults = new ArrayList<>(); - - private static IDistributionClientResult buildSuccessResult() { - return new IDistributionClientResult() { - - @Override - public String getDistributionMessageResult() { - return ""; - } - - @Override - public DistributionActionResultEnum getDistributionActionResult() { - return DistributionActionResultEnum.SUCCESS; - } - }; - } - - private NotificationConsumer createNotificationConsumer() { - return new NotificationConsumer(cambriaConsumer, clientCallback, artifactsTypes, distributionClient); - } - - @BeforeEach - public void beforeTest() throws IOException { - Mockito.reset(clientCallback, distributionClient); - when(cambriaConsumer.fetch()).then((Answer<Iterable<String>>) invocation -> { - if (!notificationsQueue.isEmpty()) { - return notificationsQueue.remove(); - } else { - return new ArrayList<>(); - } - }); - when(distributionClient.sendNotificationStatus(anyLong(), anyString(), any(ArtifactInfoImpl.class), anyBoolean())) - .then((Answer<IDistributionClientResult>) invocation -> { - boolean isNotified = (boolean) invocation.getArguments()[3]; - notificationStatusResults.add(isNotified); - return DISTRIBUTION_SUCCESS_RESULT; - }); - - } - - @Test - void testNoNotificationsSent() { - ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); - ScheduledFuture<?> scheduledFuture = executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); - await().atMost(Durations.ONE_SECOND).until(() -> !scheduledFuture.isDone()); - executorPool.shutdown(); - - Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(any(INotificationData.class)); - } - - @Test - void testNonRelevantNotificationSent() throws InterruptedException { - - simulateNotificationFromUEB(getAsdcServiceNotificationWithoutHeatArtifact()); - Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(any(INotificationData.class)); - } - - @Test - void testRelevantNotificationSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); - Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(any(INotificationData.class)); - } - - @Test - void testNonExistingArtifactsNotificationSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcNotificationWithNonExistentArtifact()); - Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(any(INotificationData.class)); - } - - @Test - void testNotificationStatusSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); - - Mockito.verify(distributionClient, Mockito.times(3)) - .sendNotificationStatus(anyLong(), anyString(), any(ArtifactInfoImpl.class), anyBoolean()); - assertEquals(1, countInstances(notificationStatusResults, Boolean.TRUE)); - assertEquals(2, countInstances(notificationStatusResults, Boolean.FALSE)); - } - - @Test - void testNotificationRelatedArtifacts() throws InterruptedException { - List<String> artifactTypesTmp = new ArrayList<>(); - for (ArtifactTypeEnum artifactTypeEnum : ArtifactTypeEnum.values()) { - artifactTypesTmp.add(artifactTypeEnum.name()); - } - artifactsTypes = artifactTypesTmp; - simulateNotificationFromUEB(getAsdcServiceNotificationWithRelatedArtifacts()); - - Mockito.verify(distributionClient, Mockito.times(3)) - .sendNotificationStatus(anyLong(), anyString(), any(ArtifactInfoImpl.class), anyBoolean()); - assertEquals(3, countInstances(notificationStatusResults, Boolean.TRUE)); - assertEquals(0, countInstances(notificationStatusResults, Boolean.FALSE)); - } - - @Test - void testNotificationStatusWithServiceArtifatcs() throws InterruptedException { - simulateNotificationFromUEB(getNotificationWithServiceArtifatcs()); - Mockito.verify(distributionClient, Mockito.times(6)) - .sendNotificationStatus(anyLong(), anyString(), any(ArtifactInfoImpl.class), anyBoolean()); - assertEquals(2, countInstances(notificationStatusResults, Boolean.TRUE)); - assertEquals(4, countInstances(notificationStatusResults, Boolean.FALSE)); - - } - - @Test - final void testBuildCallbackNotificationLogicFlagIsFalse() { - NotificationConsumer consumer = createNotificationConsumer(); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - TestConfiguration testConfiguration = new TestConfiguration(); - testConfiguration.setFilterInEmptyResources(false); - when(distributionClient.getConfiguration()).thenReturn(testConfiguration); - NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); - NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); - assertEquals(1, notificationBuiltInClient.getResources().size()); - } - - @Test - final void testBuildCallbackNotificationLogicFlagIsTrue() { - NotificationConsumer consumer = createNotificationConsumer(); - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - TestConfiguration testConfiguration = new TestConfiguration(); - testConfiguration.setFilterInEmptyResources(true); - when(distributionClient.getConfiguration()).thenReturn(testConfiguration); - NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); - NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); - assertEquals(2, notificationBuiltInClient.getResources().size()); - } - - private void simulateNotificationFromUEB(final String notificationFromUEB) throws InterruptedException { - ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); - ScheduledFuture<?> scheduledFuture = executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); - - await().atMost(Durations.TWO_HUNDRED_MILLISECONDS).until(() -> !scheduledFuture.isDone()); - - List<String> nonHeatNotification = Collections.singletonList(notificationFromUEB); - notificationsQueue.add(nonHeatNotification); - Thread.sleep(800); - executorPool.shutdown(); - } - - private String getAsdcServiceNotificationWithHeatArtifact() { - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" - + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" - + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" - + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" - + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" - + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactType\" : \"YANG_XML\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" - + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" - + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" - + " \"artifactType\" : \"HEAT_ENV\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" - + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" - + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" - + " }\r\n" + " ]}"; - } - - private String getNotificationWithMultipleResources() { - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + - " \"serviceName\" : \"Testnotificationser1\",\r\n" + - " \"serviceVersion\" : \"1.0\",\r\n" + - " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + - " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + - " \"resources\" : [{\r\n" + - " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + - " \"resourceName\" : \"TestNotificationVF1\",\r\n" + - " \"resourceVersion\" : \"1.0\",\r\n" + - " \"resoucreType\" : \"VF\",\r\n" + - " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + - " \"artifacts\" : [{\r\n" + - " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + - " \"artifactType\" : \"YANG_XML\",\r\n" + - " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + - " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + - " \"artifactDescription\" : \"MyYang\",\r\n" + - " \"artifactTimeout\" : 0,\r\n" + - " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + - " \"artifactVersion\" : \"1\"\r\n" + - " }" + - " ]\r\n" + - " },\r\n" + - " {\r\n" + - " \"resourceInstanceName\" : \"testnotificationvf12\",\r\n" + - " \"resourceName\" : \"TestNotificationVF1\",\r\n" + - " \"resourceVersion\" : \"1.0\",\r\n" + - " \"resoucreType\" : \"VF\",\r\n" + - " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2e\",\r\n" + - " \"artifacts\" : [{\r\n" + - " \"artifactName\" : \"heat.yaml\",\r\n" + - " \"artifactType\" : \"HEAT\",\r\n" + - " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + - " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + - " \"artifactDescription\" : \"heat\",\r\n" + - " \"artifactTimeout\" : 60,\r\n" + - " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + - " \"artifactVersion\" : \"1\"\r\n" + - " }" + - " ]\r\n" + - " }\r\n" + - " ]}"; - } - - - private String getAsdcNotificationWithNonExistentArtifact() { - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" - + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" - + " \"bugabuga\" : \"xyz\",\r\n" + " \"resources\" : [{\r\n" - + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + " \"resourceName\" : \"TestNotificationVF1\",\r\n" - + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" - + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + " \"artifacts\" : [{\r\n" - + " \"artifactName\" : \"heat.yaml\",\r\n" + " \"artifactType\" : \"HEAT\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" - + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" - + " \"artifactBuga\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"buga.bug\",\r\n" + " \"artifactType\" : \"BUGA_BUGA\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" - + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" - + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" - + " }\r\n" + " ]}"; - } - - private String getAsdcServiceNotificationWithRelatedArtifacts() { - return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" - + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" - + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" - + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" - + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" - + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactType\" : \"YANG_XML\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" - + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" - + " \"relatedArtifacts\" : [\r\n" - + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" + " ]" + " }, {\r\n" - + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" - + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\", \r\n" - + " \"relatedArtifacts\" : [\r\n" - + " \"0005bc4a-2c19-452e-be6d-d574a56be4d0\", \r\n" + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" - + " ]" + " }, {\r\n" - + " \"artifactName\" : \"heat.env\",\r\n" + " \"artifactType\" : \"HEAT_ENV\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" - + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" - + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" - + " }\r\n" + " ]}"; - } - - private String getAsdcServiceNotificationWithoutHeatArtifact() { - return "{" + " \"distributionID\" : \"5v1234d8-5b6d-42c4-7t54-47v95n58qb7\"," + " \"serviceName\" : \"srv1\"," - + " \"serviceVersion\": \"2.0\"," + " \"serviceUUID\" : \"4e0697d8-5b6d-42c4-8c74-46c33d46624c\"," - + " \"serviceArtifacts\":[" + " {" + " \"artifactName\" : \"ddd.yml\"," - + " \"artifactType\" : \"DG_XML\"," + " \"artifactTimeout\" : \"65\"," - + " \"artifactDescription\" : \"description\"," + " \"artifactURL\" :" - + " \"/sdc/v1/catalog/services/srv1/2.0/resources/ddd/3.0/artifacts/ddd.xml\" ," - + " \"resourceUUID\" : \"4e5874d8-5b6d-42c4-8c74-46c33d90drw\" ," - + " \"checksum\" : \"15e389rnrp58hsw==\"" + " }" + " ]" + "}"; - } - - private String getNotificationWithServiceArtifatcs() { - return "{\r\n" + " \"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" - + " \"serviceVersion\" : \"1.0\",\r\n" - + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" - + " \"serviceArtifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactType\" : \"YANG_XML\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" - + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" - + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" - + " \"artifactType\" : \"HEAT_ENV\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" - + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" - + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ],\r\n" - + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" - + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" - + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" - + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactType\" : \"YANG_XML\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" - + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" - + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" - + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" - + " \"artifactType\" : \"HEAT\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" - + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" - + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" - + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" - + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" - + " \"artifactType\" : \"HEAT_ENV\",\r\n" - + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" - + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" - + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" - + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" - + " \"artifactVersion\" : \"1\",\r\n" - + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" - + " ]\r\n" + "}"; - } - - private <T> int countInstances(List<T> list, T element) { - int count = 0; - for (T curr : list) { - if (curr.equals(element)) { - count++; - } - } - return count; - } -} + private final SdcKafkaConsumer consumer = mock(SdcKafkaConsumer.class); + private final INotificationCallback clientCallback = spy(INotificationCallback.class); + private final Queue<Iterable<String>> notificationsQueue = new LinkedList<>(); + private final DistributionClientImpl distributionClient = Mockito.spy(DistributionClientImpl.class); + private List<String> artifactsTypes = List.of(ArtifactTypeEnum.HEAT.name()); + private final List<Boolean> notificationStatusResults = new ArrayList<>(); + final static IDistributionClientResult DISTRIBUTION_SUCCESS_RESULT = buildSuccessResult(); + + private NotificationConsumer createNotificationConsumer() { + return new NotificationConsumer(consumer, clientCallback, artifactsTypes, distributionClient); + } + + @BeforeEach + public void beforeTest() { + Mockito.reset(clientCallback, distributionClient); + when(consumer.poll()).then((Answer<Iterable<String>>) invocation -> { + if (!notificationsQueue.isEmpty()) { + return notificationsQueue.remove(); + } else { + return new ArrayList<>(); + } + }); + when(distributionClient.sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean())).then( + (Answer<IDistributionClientResult>) invocation -> { + boolean isNotified = (boolean) invocation.getArguments()[3]; + notificationStatusResults.add(isNotified); + return DISTRIBUTION_SUCCESS_RESULT; + }); + + } + + private static IDistributionClientResult buildSuccessResult() { + return new IDistributionClientResult() { + + @Override + public String getDistributionMessageResult() { + return ""; + } + + @Override + public DistributionActionResultEnum getDistributionActionResult() { + return DistributionActionResultEnum.SUCCESS; + } + }; + } + + @Test + void testNoNotifiactionsSent() throws InterruptedException { + + ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); + executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); + + Thread.sleep(1000); + executorPool.shutdown(); + + Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + void testNonRelevantNotificationSent() throws InterruptedException { + + simulateNotificationFromMessageBus(getSdcServiceNotificationWithoutHeatArtifact()); + Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + void testRelevantNotificationSent() throws InterruptedException { + simulateNotificationFromMessageBus(getSdcServiceNotificationWithHeatArtifact()); + Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + void testNonExistingArtifactsNotificationSent() throws InterruptedException { + simulateNotificationFromMessageBus(getSdcNotificationWithNonExistentArtifact()); + Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); + + } + + @Test + void testNotificationStatusSent() throws InterruptedException { + simulateNotificationFromMessageBus(getSdcServiceNotificationWithHeatArtifact()); + + Mockito.verify(distributionClient, Mockito.times(3)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); + assertEquals(1, countInstances(notificationStatusResults, Boolean.TRUE)); + assertEquals(2, countInstances(notificationStatusResults, Boolean.FALSE)); + } + + @Test + void testNotificationRelatedArtifacts() throws InterruptedException { + List<String> artifactTypesTmp = new ArrayList<>(); + for (ArtifactTypeEnum artifactTypeEnum : ArtifactTypeEnum.values()) { + artifactTypesTmp.add(artifactTypeEnum.name()); + } + artifactsTypes = artifactTypesTmp; + simulateNotificationFromMessageBus(getSdcServiceNotificationWithRelatedArtifacts()); + + Mockito.verify(distributionClient, Mockito.times(3)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); + assertEquals(3, countInstances(notificationStatusResults, Boolean.TRUE)); + assertEquals(0, countInstances(notificationStatusResults, Boolean.FALSE)); + } + + @Test + void testNotificationStatusWithServiceArtifatcs() throws InterruptedException { + simulateNotificationFromMessageBus(getNotificationWithServiceArtifatcs()); + Mockito.verify(distributionClient, Mockito.times(6)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); + assertEquals(2, countInstances(notificationStatusResults, Boolean.TRUE)); + assertEquals(4, countInstances(notificationStatusResults, Boolean.FALSE)); + + } + + @Test + final void testBuildCallbackNotificationLogicFlagIsFalse() { + NotificationConsumer consumer = createNotificationConsumer(); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + TestConfiguration testConfiguration = new TestConfiguration(); + testConfiguration.setFilterInEmptyResources(false); + when(distributionClient.getConfiguration()).thenReturn(testConfiguration); + NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); + NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); + assertEquals(1, notificationBuiltInClient.getResources().size()); + } + + @Test + final void testBuildCallbackNotificationLogicFlagIsTrue() { + NotificationConsumer consumer = createNotificationConsumer(); + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + TestConfiguration testConfiguration = new TestConfiguration(); + testConfiguration.setFilterInEmptyResources(true); + when(distributionClient.getConfiguration()).thenReturn(testConfiguration); + NotificationDataImpl notification = gson.fromJson(getNotificationWithMultipleResources(), NotificationDataImpl.class); + NotificationDataImpl notificationBuiltInClient = consumer.buildCallbackNotificationLogic(0, notification); + assertEquals(2, notificationBuiltInClient.getResources().size()); + } + + private void simulateNotificationFromMessageBus(final String notificationFromMessageBus) throws InterruptedException { + ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); + executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); + + Thread.sleep(200); + + List<String> nonHeatNotification = List.of(notificationFromMessageBus); + notificationsQueue.add(nonHeatNotification); + Thread.sleep(800); + executorPool.shutdown(); + } + + private String getSdcServiceNotificationWithHeatArtifact() { + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" + + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; + } + + private String getNotificationWithMultipleResources(){ + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + + " \"serviceName\" : \"Testnotificationser1\",\r\n" + + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + + " \"resources\" : [{\r\n" + + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + + " \"resourceVersion\" : \"1.0\",\r\n" + + " \"resoucreType\" : \"VF\",\r\n" + + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + + " \"artifactDescription\" : \"MyYang\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + + " \"artifactVersion\" : \"1\"\r\n" + + " }" + + " ]\r\n" + + " },\r\n" + + " {\r\n" + + " \"resourceInstanceName\" : \"testnotificationvf12\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + + " \"resourceVersion\" : \"1.0\",\r\n" + + " \"resoucreType\" : \"VF\",\r\n" + + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2e\",\r\n" + + " \"artifacts\" : [{\r\n" + + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + + " \"artifactDescription\" : \"heat\",\r\n" + + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + + " \"artifactVersion\" : \"1\"\r\n" + + " }" + + " ]\r\n" + + " }\r\n" + + " ]}"; + } + + + private String getSdcNotificationWithNonExistentArtifact() { + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"bugabuga\" : \"xyz\",\r\n" + " \"resources\" : [{\r\n" + + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + " \"artifactType\" : \"HEAT\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactBuga\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + + " }, {\r\n" + " \"artifactName\" : \"buga.bug\",\r\n" + " \"artifactType\" : \"BUGA_BUGA\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; + } + + private String getSdcServiceNotificationWithRelatedArtifacts() { + return "{\"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + " \"relatedArtifacts\" : [\r\n" + + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" + " ]" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\", \r\n" + " \"relatedArtifacts\" : [\r\n" + + " \"0005bc4a-2c19-452e-be6d-d574a56be4d0\", \r\n" + " \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\"\r\n" + " ]" + " }, {\r\n" + + " \"artifactName\" : \"heat.env\",\r\n" + " \"artifactType\" : \"HEAT_ENV\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]}"; + } + + private String getSdcServiceNotificationWithoutHeatArtifact() { + return "{" + " \"distributionID\" : \"5v1234d8-5b6d-42c4-7t54-47v95n58qb7\"," + " \"serviceName\" : \"srv1\"," + " \"serviceVersion\": \"2.0\"," + " \"serviceUUID\" : \"4e0697d8-5b6d-42c4-8c74-46c33d46624c\"," + + " \"serviceArtifacts\":[" + " {" + " \"artifactName\" : \"ddd.yml\"," + " \"artifactType\" : \"DG_XML\"," + " \"artifactTimeout\" : \"65\"," + + " \"artifactDescription\" : \"description\"," + " \"artifactURL\" :" + " \"/sdc/v1/catalog/services/srv1/2.0/resources/ddd/3.0/artifacts/ddd.xml\" ," + + " \"resourceUUID\" : \"4e5874d8-5b6d-42c4-8c74-46c33d90drw\" ," + " \"checksum\" : \"15e389rnrp58hsw==\"" + " }" + " ]" + "}"; + } + + private String getNotificationWithServiceArtifatcs() { + return "{\r\n" + " \"distributionID\" : \"bcc7a72e-90b1-4c5f-9a37-28dc3cd86416\",\r\n" + " \"serviceName\" : \"Testnotificationser1\",\r\n" + " \"serviceVersion\" : \"1.0\",\r\n" + + " \"serviceUUID\" : \"7f7f94f4-373a-4b71-a0e3-80ae2ba4eb5d\",\r\n" + " \"serviceDescription\" : \"TestNotificationVF1\",\r\n" + " \"serviceArtifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactType\" : \"YANG_XML\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" + + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ],\r\n" + " \"resources\" : [{\r\n" + " \"resourceInstanceName\" : \"testnotificationvf11\",\r\n" + + " \"resourceName\" : \"TestNotificationVF1\",\r\n" + " \"resourceVersion\" : \"1.0\",\r\n" + " \"resoucreType\" : \"VF\",\r\n" + " \"resourceUUID\" : \"907e1746-9f69-40f5-9f2a-313654092a2d\",\r\n" + + " \"artifacts\" : [{\r\n" + " \"artifactName\" : \"sample-xml-alldata-1-1.xml\",\r\n" + " \"artifactType\" : \"YANG_XML\",\r\n" + + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/sample-xml-alldata-1-1.xml\",\r\n" + + " \"artifactChecksum\" : \"MTUxODFkMmRlOTNhNjYxMGYyYTI1ZjA5Y2QyNWQyYTk\\u003d\",\r\n" + " \"artifactDescription\" : \"MyYang\",\r\n" + " \"artifactTimeout\" : 0,\r\n" + + " \"artifactUUID\" : \"0005bc4a-2c19-452e-be6d-d574a56be4d0\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.yaml\",\r\n" + + " \"artifactType\" : \"HEAT\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.yaml\",\r\n" + + " \"artifactChecksum\" : \"ODEyNjE4YTMzYzRmMTk2ODVhNTU2NTg3YWEyNmIxMTM\\u003d\",\r\n" + " \"artifactDescription\" : \"heat\",\r\n" + " \"artifactTimeout\" : 60,\r\n" + + " \"artifactUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\",\r\n" + " \"artifactVersion\" : \"1\"\r\n" + " }, {\r\n" + " \"artifactName\" : \"heat.env\",\r\n" + + " \"artifactType\" : \"HEAT_ENV\",\r\n" + " \"artifactURL\" : \"/sdc/v1/catalog/services/Testnotificationser1/1.0/resourceInstances/testnotificationvf11/artifacts/heat.env\",\r\n" + + " \"artifactChecksum\" : \"NGIzMjExZTM1NDc2NjBjOTQyMGJmMWNiMmU0NTE5NzM\\u003d\",\r\n" + " \"artifactDescription\" : \"Auto-generated HEAT Environment deployment artifact\",\r\n" + + " \"artifactTimeout\" : 0,\r\n" + " \"artifactUUID\" : \"ce65d31c-35c0-43a9-90c7-596fc51d0c86\",\r\n" + " \"artifactVersion\" : \"1\",\r\n" + + " \"generatedFromUUID\" : \"8df6123c-f368-47d3-93be-1972cefbcc35\"\r\n" + " }\r\n" + " ]\r\n" + " }\r\n" + " ]\r\n" + "}"; + } + + private <T> int countInstances(List<T> list, T element) { + int count = 0; + for (T curr : list) { + if (curr.equals(element)) { + count++; + } + } + return count; + } +}
\ No newline at end of file diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/NotificationSenderTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/NotificationSenderTest.java index 4d61542..ed15094 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/NotificationSenderTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/NotificationSenderTest.java @@ -20,115 +20,71 @@ package org.onap.sdc.utils; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaPublisher; -import java.io.IOException; -import java.util.Collections; -import java.util.List; +import java.util.concurrent.Future; +import nl.altindag.log.LogCaptor; +import org.apache.kafka.common.KafkaException; import org.junit.jupiter.api.Test; import org.onap.sdc.api.results.IDistributionClientResult; import org.onap.sdc.impl.DistributionClientResultImpl; +import org.onap.sdc.utils.kafka.SdcKafkaProducer; class NotificationSenderTest { private final String status = "status"; - private final CambriaPublisher.message message = new CambriaPublisher.message("sample-partition", "sample-message"); - private final List<CambriaPublisher.message> notEmptySendingFailedMessages = Collections.singletonList(message); + private final DistributionClientResultImpl successResponse = new DistributionClientResultImpl(DistributionActionResultEnum.SUCCESS, "Messages successfully sent"); - private final DistributionClientResultImpl generalErrorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, - "Failed to send status"); - - private final CambriaBatchingPublisher publisher = mock(CambriaBatchingPublisher.class); - private final List<String> emptyServers = Collections.emptyList(); - private final NotificationSender validNotificationSender = new NotificationSender(emptyServers); + private final DistributionClientResultImpl generalErrorResponse = new DistributionClientResultImpl(DistributionActionResultEnum.GENERAL_ERROR, "Failed to send status"); + private final SdcKafkaProducer producer = mock(SdcKafkaProducer.class); + private final NotificationSender validNotificationSender = new NotificationSender(producer); @Test - void whenPublisherIsValidAndNoExceptionsAreThrownShouldReturnSuccessStatus() throws IOException, InterruptedException { + void whenPublisherIsValidAndNoExceptionsAreThrownShouldReturnSuccessStatus() { //given - when(publisher.send(anyString(), anyString())).thenReturn(0); - when(publisher.close(anyLong(), any())).thenReturn(Collections.emptyList()); + when(producer.send(anyString(), anyString(), anyString())).thenReturn(mock(Future.class)); //when - IDistributionClientResult result = validNotificationSender.send(publisher, status); + IDistributionClientResult result = validNotificationSender.send("mytopic", status); //then assertEquals(successResponse.getDistributionActionResult(), result.getDistributionActionResult()); } @Test - void whenPublisherCouldNotSendShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { + void whenPublisherCouldNotSendShouldReturnGeneralErrorStatus() { //given - when(publisher.send(anyString(), anyString())).thenReturn(0); - when(publisher.close(anyLong(), any())).thenReturn(notEmptySendingFailedMessages); + when(producer.send(anyString(), anyString(), anyString())).thenReturn(mock(Future.class)); + doThrow(KafkaException.class) + .when(producer) + .flush(); //when - IDistributionClientResult result = validNotificationSender.send(publisher, status); + IDistributionClientResult result = validNotificationSender.send("mytopic", status); //then assertEquals(generalErrorResponse.getDistributionActionResult(), result.getDistributionActionResult()); } @Test - void whenSendingThrowsIOExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { - //given - when(publisher.send(anyString(), anyString())).thenThrow(new IOException()); - when(publisher.close(anyLong(), any())).thenReturn(notEmptySendingFailedMessages); - - //when - IDistributionClientResult result = validNotificationSender.send(publisher, status); + void whenSendingThrowsIOExceptionShouldReturnGeneralErrorStatus() { + LogCaptor logCaptor = LogCaptor.forClass(NotificationSender.class); - //then - assertEquals(generalErrorResponse.getDistributionActionResult(), result.getDistributionActionResult()); - } - - @Test - void whenSendingThrowsInterruptedExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { //given - when(publisher.send(anyString(), anyString())).thenAnswer(invocationOnMock -> { - throw new InterruptedException(); - }); - when(publisher.close(anyLong(), any())).thenReturn(notEmptySendingFailedMessages); + when(producer.send(anyString(), anyString(), anyString())).thenThrow(new KafkaException()); //when - IDistributionClientResult result = validNotificationSender.send(publisher, status); + validNotificationSender.send("mytopic", status); //then - assertEquals(generalErrorResponse.getDistributionActionResult(), result.getDistributionActionResult()); + assertThat(logCaptor.getLogs()).contains("DistributionClient - sendStatus. Failed to send status"); } - @Test - void whenClosingThrowsIOExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { - //given - when(publisher.send(anyString(), anyString())).thenReturn(0); - when(publisher.close(anyLong(), any())).thenThrow(new IOException()); - - //when - IDistributionClientResult result = validNotificationSender.send(publisher, status); - - //then - assertEquals(generalErrorResponse.getDistributionActionResult(), result.getDistributionActionResult()); - } - - @Test - void whenClosingThrowsInterruptedExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { - //given - when(publisher.send(anyString(), anyString())).thenReturn(0); - when(publisher.close(anyLong(), any())).thenAnswer(invocationOnMock -> { - throw new InterruptedException(); - }); - - //when - IDistributionClientResult result = validNotificationSender.send(publisher, status); - - //then - assertEquals(generalErrorResponse.getDistributionActionResult(), result.getDistributionActionResult()); - } } + diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/SdcKafkaTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/SdcKafkaTest.java new file mode 100644 index 0000000..744e9cc --- /dev/null +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/SdcKafkaTest.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * sdc-distribution-client + * ================================================================================ + * Copyright (C) 2022 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.sdc.utils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.contentOf; + +import com.salesforce.kafka.test.KafkaTestCluster; +import com.salesforce.kafka.test.KafkaTestUtils; +import com.salesforce.kafka.test.listeners.BrokerListener; +import com.salesforce.kafka.test.listeners.SaslPlainListener; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.SetEnvironmentVariable; +import org.onap.sdc.api.consumer.IConfiguration; +import org.onap.sdc.impl.Configuration; +import org.onap.sdc.utils.kafka.SdcKafkaConsumer; +import org.onap.sdc.utils.kafka.SdcKafkaProducer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@SetEnvironmentVariable(key = "SASL_JAAS_CONFIG", value = "org.apache.kafka.common.security.scram.ScramLoginModule required username=admin password=admin-secret;") +class SdcKafkaTest { + + private static final Logger logger = LoggerFactory.getLogger(SdcKafkaTest.class); + + private static final Configuration configuration = new Configuration(new TestConfiguration()); + private static KafkaTestCluster kafkaTestCluster = null; + private static final String topicName = "my-test-topic"; + + static { + System.setProperty("java.security.auth.login.config", "src/test/resources/jaas.conf"); + } + + @BeforeAll + static void before() throws Exception { + startKafkaService(); + KafkaTestUtils utils = new KafkaTestUtils(kafkaTestCluster); + utils.createTopic(topicName, 1, (short) 1); + configuration.setMsgBusAddress(Collections.singletonList(kafkaTestCluster.getKafkaConnectString())); + } + + @AfterAll + static void after() throws Exception { + kafkaTestCluster.close(); + kafkaTestCluster.stop(); + } + + @Test + void whenProducingCorrectRecordsArePresent() { + SdcKafkaConsumer consumer = new SdcKafkaConsumer(configuration); + consumer.subscribe(topicName); + consumer.poll(); + + SdcKafkaProducer producer = new SdcKafkaProducer(configuration); + producer.send(topicName, "blah", "blah"); + producer.send(topicName, "blah", "blah"); + producer.send(topicName, "blah", "blah"); + producer.flush(); + + List<String> events = consumer.poll(); + + assertThat(events).hasSize(3); + } + + private static void startKafkaService() throws Exception { + final BrokerListener listener = new SaslPlainListener() + .withUsername("kafkaclient") + .withPassword("client-secret"); + + final Properties brokerProperties = new Properties(); + kafkaTestCluster = new KafkaTestCluster( + 1, + brokerProperties, + Collections.singletonList(listener) + ); + + kafkaTestCluster.start(); + logger.debug("Cluster started at: {}", kafkaTestCluster.getKafkaConnectString()); + } +}
\ No newline at end of file diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java index ca7abba..c2fc536 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/TestConfiguration.java @@ -22,12 +22,11 @@ package org.onap.sdc.utils; import java.util.ArrayList; import java.util.List; - import org.onap.sdc.api.consumer.IConfiguration; public class TestConfiguration implements IConfiguration { - private String asdcAddress; + private String sdcAddress; private String user; private String password; private int pollingInterval = DistributionClientConstants.MIN_POLLING_INTERVAL_SEC; @@ -36,11 +35,13 @@ public class TestConfiguration implements IConfiguration { private String consumerGroup; private String environmentName; private String comsumerID; + private final String kafkaSecurityProtocolConfig; + private final String kafkaSaslMechanism; + private final String kafkaSaslJaasConfig; private String keyStorePath; private String keyStorePassword; private boolean activateServerTLSAuth; private boolean isFilterInEmptyResources; - private boolean useHttpsWithDmaap; private boolean useHttpsWithSDC; private List<String> msgBusAddress; private String httpProxyHost; @@ -48,11 +49,16 @@ public class TestConfiguration implements IConfiguration { private String httpsProxyHost; private int httpsProxyPort; private boolean useSystemProxy; + private String sdcStatusTopicName; + private String sdcNotificationTopicName; public TestConfiguration(IConfiguration other) { - this.asdcAddress = other.getAsdcAddress(); + this.sdcAddress = other.getSdcAddress(); this.comsumerID = other.getConsumerID(); this.consumerGroup = other.getConsumerGroup(); + this.kafkaSecurityProtocolConfig = other.getKafkaSecurityProtocolConfig(); + this.kafkaSaslMechanism = other.getKafkaSaslMechanism(); + this.kafkaSaslJaasConfig = other.getKafkaSaslJaasConfig(); this.environmentName = other.getEnvironmentName(); this.password = other.getPassword(); this.pollingInterval = other.getPollingInterval(); @@ -71,30 +77,37 @@ public class TestConfiguration implements IConfiguration { } public TestConfiguration() { - this.asdcAddress = "localhost:8443"; + this.sdcAddress = "localhost:8443"; this.comsumerID = "mso-123456"; this.consumerGroup = "mso-group"; this.environmentName = "PROD"; this.password = "password"; this.pollingInterval = 20; this.pollingTimeout = 20; - this.relevantArtifactTypes = new ArrayList<String>(); + this.setSdcStatusTopicName("SDC-STATUS-TOPIC"); + this.setSdcNotificationTopicName("SDC-NOTIF-TOPIC"); + this.relevantArtifactTypes = new ArrayList<>(); this.relevantArtifactTypes.add(ArtifactTypeEnum.HEAT.name()); this.user = "mso-user"; - this.keyStorePath = "etc/asdc-client.jks"; + this.keyStorePath = "etc/sdc-client.jks"; this.keyStorePassword = "Aa123456"; this.activateServerTLSAuth = false; this.isFilterInEmptyResources = false; this.useHttpsWithSDC = true; - msgBusAddress = new ArrayList<String>(); - msgBusAddress.add("www.cnn.com"); - msgBusAddress.add("www.cnn.com"); - msgBusAddress.add("www.cnn.com"); + msgBusAddress = new ArrayList<>(); + msgBusAddress.add("kafka-bootstrap1:9092"); + msgBusAddress.add("kafka-bootstrap2:9092"); + msgBusAddress.add("kafka-bootstrap3:9092"); + this.kafkaSecurityProtocolConfig = "SASL_PLAINTEXT"; + this.kafkaSaslMechanism = "PLAIN"; + this.kafkaSaslJaasConfig = "org.apache.kafka.common.security.scram.ScramLoginModule required username=admin password=admin-secret;"; + this.httpProxyHost = "proxy"; + this.httpProxyPort = 8080; } @Override - public String getAsdcAddress() { - return asdcAddress; + public String getSdcAddress() { + return sdcAddress; } @Override @@ -103,6 +116,21 @@ public class TestConfiguration implements IConfiguration { } @Override + public String getKafkaSecurityProtocolConfig() { + return kafkaSecurityProtocolConfig; + } + + @Override + public String getKafkaSaslMechanism() { + return kafkaSaslMechanism; + } + + @Override + public String getKafkaSaslJaasConfig() { + return kafkaSaslJaasConfig; + } + + @Override public String getUser() { return user; } @@ -185,8 +213,8 @@ public class TestConfiguration implements IConfiguration { this.comsumerID = comsumerID; } - public void setAsdcAddress(String asdcAddress) { - this.asdcAddress = asdcAddress; + public void setSdcAddress(String sdcAddress) { + this.sdcAddress = sdcAddress; } public void setUser(String user) { @@ -249,7 +277,7 @@ public class TestConfiguration implements IConfiguration { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((asdcAddress == null) ? 0 : asdcAddress.hashCode()); + result = prime * result + ((sdcAddress == null) ? 0 : sdcAddress.hashCode()); result = prime * result + ((comsumerID == null) ? 0 : comsumerID.hashCode()); result = prime * result + ((consumerGroup == null) ? 0 : consumerGroup.hashCode()); result = prime * result + ((environmentName == null) ? 0 : environmentName.hashCode()); @@ -280,10 +308,10 @@ public class TestConfiguration implements IConfiguration { if (getClass() != obj.getClass()) return false; TestConfiguration other = (TestConfiguration) obj; - if (asdcAddress == null) { - if (other.asdcAddress != null) + if (sdcAddress == null) { + if (other.sdcAddress != null) return false; - } else if (!asdcAddress.equals(other.asdcAddress)) + } else if (!sdcAddress.equals(other.sdcAddress)) return false; if (comsumerID == null) { if (other.comsumerID != null) @@ -325,17 +353,14 @@ public class TestConfiguration implements IConfiguration { } else if (!keyStorePath.equals(other.keyStorePath)) return false; if (keyStorePassword == null) { - if (other.keyStorePassword != null) - return false; - } else if (!keyStorePassword.equals(other.keyStorePassword)) - return false; - - return true; + return other.keyStorePassword == null; + } else + return keyStorePassword.equals(other.keyStorePassword); } @Override public String toString() { - return "TestConfiguration [asdcAddress=" + asdcAddress + ", user=" + user + ", password=" + password + return "TestConfiguration [sdcAddress=" + sdcAddress + ", user=" + user + ", password=" + password + ", pollingInterval=" + pollingInterval + ", pollingTimeout=" + pollingTimeout + ", relevantArtifactTypes=" + relevantArtifactTypes + ", consumerGroup=" + consumerGroup + ", environmentName=" + environmentName + ", comsumerID=" + comsumerID + "]"; @@ -351,11 +376,6 @@ public class TestConfiguration implements IConfiguration { } @Override - public Boolean isUseHttpsWithDmaap() { - return this.useHttpsWithDmaap; - } - - @Override public Boolean isUseHttpsWithSDC() { return this.useHttpsWithSDC; } @@ -363,4 +383,20 @@ public class TestConfiguration implements IConfiguration { public void setUseHttpsWithSDC(Boolean useHttpsWithSDC) { this.useHttpsWithSDC = useHttpsWithSDC; } + + public String getSdcStatusTopicName() { + return sdcStatusTopicName; + } + + public void setSdcStatusTopicName(String sdcStatusTopicName) { + this.sdcStatusTopicName = sdcStatusTopicName; + } + + public String getSdcNotificationTopicName() { + return sdcNotificationTopicName; + } + + public void setSdcNotificationTopicName(String sdcNotificationTopicName) { + this.sdcNotificationTopicName = sdcNotificationTopicName; + } } |