diff options
author | vasraz <vasyl.razinkov@est.tech> | 2022-08-29 16:13:33 +0100 |
---|---|---|
committer | Vasyl Razinkov <vasyl.razinkov@est.tech> | 2022-08-29 16:43:31 +0000 |
commit | 1b46a6e1d6fcf9788c9f18552f6f6b8fed60126c (patch) | |
tree | 4e63a047fb758bc15aa4594202a4ade33aeb9f47 | |
parent | cc595a0bfd90645b451ddee658fc496624072cea (diff) |
Migrate to Junit5
Signed-off-by: Vasyl Razinkov <vasyl.razinkov@est.tech>
Change-Id: I00d5d08f0ad3ceeec94286f6500c4592585e7e34
Issue-ID: SDC-4148
22 files changed, 1280 insertions, 1372 deletions
@@ -47,6 +47,8 @@ <mockito.version>3.12.4</mockito.version> <slf4j-api.version>1.7.36</slf4j-api.version> <assertj-core.version>3.23.1</assertj-core.version> + <awaitility-proxy.version>3.1.6</awaitility-proxy.version> + <awaitility.version>4.2.0</awaitility.version> <nexus.proxy>https://nexus.onap.org</nexus.proxy> <sitePath>/content/sites/site/org/onap/sdc/sdc-distribution-client/${project.version}</sitePath> @@ -235,6 +237,4 @@ </site> </distributionManagement> - </project> - diff --git a/sdc-distribution-ci/pom.xml b/sdc-distribution-ci/pom.xml index 97ed30b..e11d428 100644 --- a/sdc-distribution-ci/pom.xml +++ b/sdc-distribution-ci/pom.xml @@ -22,8 +22,6 @@ <junit-jupiter-engine.version>${junit.version}</junit-jupiter-engine.version> <junit-jupiter-params.version>${junit.version}</junit-jupiter-params.version> <junit-jupiter-api.version>${junit.version}</junit-jupiter-api.version> - <awaitility-proxy.version>3.0.0</awaitility-proxy.version> - <awaitility.version>3.0.0</awaitility.version> </properties> <dependencies> @@ -178,18 +176,6 @@ </exclusions> </dependency> <dependency> - <groupId>org.awaitility</groupId> - <artifactId>awaitility-proxy</artifactId> - <version>${awaitility-proxy.version}</version> - <scope>test</scope> - <exclusions> - <exclusion> - <artifactId>byte-buddy</artifactId> - <groupId>net.bytebuddy</groupId> - </exclusion> - </exclusions> - </dependency> - <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> diff --git a/sdc-distribution-ci/src/test/java/org/onap/test/core/service/ClientInitializerTest.java b/sdc-distribution-ci/src/test/java/org/onap/test/core/service/ClientInitializerTest.java index 797009d..ba118c0 100644 --- a/sdc-distribution-ci/src/test/java/org/onap/test/core/service/ClientInitializerTest.java +++ b/sdc-distribution-ci/src/test/java/org/onap/test/core/service/ClientInitializerTest.java @@ -19,7 +19,19 @@ */ package org.onap.test.core.service; -import org.awaitility.Duration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import org.awaitility.Durations; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -37,19 +49,6 @@ import org.testcontainers.containers.GenericContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.mockito.Mockito.verify; - @Testcontainers @ExtendWith(MockitoExtension.class) class ClientInitializerTest { @@ -59,24 +58,19 @@ class ClientInitializerTest { private static final int SUCCESSFUL_INIT_MSG_INDEX = 0; private static final int SUCCESSFUL_DIST_MSG_INDEX = 3; private static final int EXPECTED_HEAT_ARTIFACTS = 4; - private ClientInitializer clientInitializer; - private ClientNotifyCallback clientNotifyCallback; private static final Logger testLog = LoggerFactory.getLogger(ClientInitializerTest.class); - @Container public GenericContainer mockDmaap = new GenericContainer("registry.gitlab.com/orange-opensource/lfn/onap/mock_servers/mock-dmaap:latest") - .withNetworkMode("host"); - - + .withNetworkMode("host"); @Container public GenericContainer mockSdc = new GenericContainer("registry.gitlab.com/orange-opensource/lfn/onap/mock_servers/mock-sdc:latest") - .withNetworkMode("host"); + .withNetworkMode("host"); @Mock - Logger log; - + private Logger log; @Mock - Logger distClientLog; - + private Logger distClientLog; + private ClientInitializer clientInitializer; + private ClientNotifyCallback clientNotifyCallback; @BeforeEach public void initializeClient() { @@ -88,7 +82,7 @@ class ClientInitializerTest { } @Test - public void shouldRegisterToDmaapAfterClientInitialization() { + void shouldRegisterToDmaapAfterClientInitialization() { //given final ArgumentCaptor<String> exceptionCaptor = ArgumentCaptor.forClass(String.class); //when @@ -102,7 +96,7 @@ class ClientInitializerTest { } @Test - public void shouldUnregisterAndStopClient() { + void shouldUnregisterAndStopClient() { //given final ArgumentCaptor<String> exceptionCaptor = ArgumentCaptor.forClass(String.class); //when @@ -116,13 +110,13 @@ class ClientInitializerTest { } @Test - public void shouldDownloadArtifactsWithArtifactTypeHeat() throws IOException, InterruptedException { + void shouldDownloadArtifactsWithArtifactTypeHeat() throws IOException, InterruptedException { //given HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create("http://localhost:3904/events/testName/add")) - .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/artifacts.json"))) - .build(); + .uri(URI.create("http://localhost:3904/events/testName/add")) + .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("src/test/resources/artifacts.json"))) + .build(); HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); //when clientInitializer.initialize(); @@ -135,7 +129,7 @@ class ClientInitializerTest { private void waitForArtifacts() { testLog.info("Waiting for artifacts"); await() - .atMost(Duration.ONE_MINUTE) - .until(() -> !clientNotifyCallback.getPulledArtifacts().isEmpty()); + .atMost(Durations.ONE_MINUTE) + .until(() -> !clientNotifyCallback.getPulledArtifacts().isEmpty()); } } diff --git a/sdc-distribution-client/pom.xml b/sdc-distribution-client/pom.xml index 7d46cc5..ef0911c 100644 --- a/sdc-distribution-client/pom.xml +++ b/sdc-distribution-client/pom.xml @@ -142,13 +142,6 @@ </exclusions> </dependency> -<!-- TODO - remove after migration to Junit5--> - <dependency> - <groupId>org.junit.vintage</groupId> - <artifactId>junit-vintage-engine</artifactId> - <version>${junit.version}</version> - <scope>test</scope> - </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> @@ -195,6 +188,18 @@ <scope>test</scope> </dependency> + <dependency> + <groupId>org.awaitility</groupId> + <artifactId>awaitility</artifactId> + <version>${awaitility.version}</version> + <scope>test</scope> + <exclusions> + <exclusion> + <artifactId>objenesis</artifactId> + <groupId>org.objenesis</groupId> + </exclusion> + </exclusions> + </dependency> </dependencies> </project> diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java index 901b067..b0cfb1e 100644 --- a/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/api/asdc/ServerListResponse.java @@ -21,16 +21,15 @@ package org.onap.sdc.api.asdc; import java.util.List; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +@Getter +@Setter +@NoArgsConstructor public class ServerListResponse { private List<String> uebServerList; - public List<String> getUebServerList() { - return uebServerList; - } - - public void setUebServerList(List<String> uebServerList) { - this.uebServerList = uebServerList; - } } diff --git a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java index de5d1ec..a8aaa33 100644 --- a/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java +++ b/sdc-distribution-client/src/main/java/org/onap/sdc/impl/StatusDataImpl.java @@ -21,9 +21,15 @@ package org.onap.sdc.impl; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import org.onap.sdc.api.notification.IStatusData; import org.onap.sdc.utils.DistributionStatusEnum; +@Getter +@Setter +@NoArgsConstructor public class StatusDataImpl implements IStatusData { private String distributionID; @@ -35,65 +41,9 @@ public class StatusDataImpl implements IStatusData { private String errorReason; @Override - public String getDistributionID() { - return distributionID; - } - - public void setDistributionID(String distributionId) { - this.distributionID = distributionId; - } - - @Override - public String getConsumerID() { - return consumerID; - } - - public void setConsumerID(String consumerId) { - this.consumerID = consumerId; - } - - @Override - public Long getTimestamp() { - return timestamp; - } - - public void setTimestamp(Long timestamp) { - this.timestamp = timestamp; - } - - @Override - public String getArtifactURL() { - return artifactURL; - } - - public void setArtifactURL(String artifactURL) { - this.artifactURL = artifactURL; - } - - @Override - public DistributionStatusEnum getStatus() { - return status; - } - - public void setStatus(DistributionStatusEnum status) { - this.status = status; - } - - - @Override public String toString() { - return "StatusDataImpl [distributionID=" + distributionID + ", consumerID=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]"; - } - - @Override - public String getComponentName() { - return componentName; + return "StatusDataImpl [distributionID=" + distributionID + ", consumerID=" + consumerID + ", timestamp=" + timestamp + ", artifactURL=" + + artifactURL + ", status=" + status + ", errorReason=" + errorReason + "]"; } - @Override - public String getErrorReason() { - return errorReason; - } - - } 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 index 50ff94c..304cb56 100644 --- 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 @@ -19,14 +19,14 @@ */ package org.onap.sdc.api.asdc; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +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.Test; +import org.junit.jupiter.api.Test; -public class RegistrationRequestTest { +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; @@ -34,12 +34,12 @@ public class RegistrationRequestTest { private static final String API_KEY = "API_KEY"; @Test - public void testConstructorShouldSetProperties() { + void testConstructorShouldSetProperties() { RegistrationRequest registrationRequest = - new RegistrationRequest(API_KEY, ENV_NAME, IS_CONSUMER_TO_SDC_DISTR_STATUS_TOPIC, DIST_ENV_END_POINTS); - assertEquals(registrationRequest.getApiPublicKey(), API_KEY); - assertEquals(registrationRequest.getDistEnvEndPoints(), DIST_ENV_END_POINTS); - assertEquals(registrationRequest.getDistrEnvName(), ENV_NAME); + 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()); } -}
\ No newline at end of file +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/api/asdc/ServerListResponseTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/api/asdc/ServerListResponseTest.java deleted file mode 100644 index 449eca8..0000000 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/api/asdc/ServerListResponseTest.java +++ /dev/null @@ -1,32 +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 com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class ServerListResponseTest { - @Test - public void shouldHaveValidGettersAndSetters() { - assertThat(ServerListResponse.class, hasValidGettersAndSetters()); - } -}
\ No newline at end of file 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 eb5c1eb..8a912d9 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 @@ -19,44 +19,39 @@ */ package org.onap.sdc.http; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpStatus; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpStatus; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.junit.jupiter.MockitoExtension; +@ExtendWith(MockitoExtension.class) +class HttpAsdcClientResponseTest { -@RunWith(value = Parameterized.class) -public class HttpAsdcClientResponseTest { - @Parameterized.Parameter - public int httpStatusCode; - - @Parameterized.Parameter(value = 1) - public String httpMessage; - - @Parameterized.Parameters(name = "{index}: test({0},{1}) = {0} {1}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ - {HttpStatus.SC_INTERNAL_SERVER_ERROR, "failed to send request"}, - {HttpStatus.SC_BAD_GATEWAY, "failed to connect"}, - {HttpStatus.SC_BAD_GATEWAY, "failed to send request "} + {HttpStatus.SC_INTERNAL_SERVER_ERROR, "failed to send request"}, + {HttpStatus.SC_BAD_GATEWAY, "failed to connect"}, + {HttpStatus.SC_BAD_GATEWAY, "failed to send request "} }); } - @Test - public void shouldCreateHttpResponse() throws IOException { + @ParameterizedTest + @MethodSource("data") + void shouldCreateHttpResponse(int httpStatusCode, String httpMessage) throws IOException { // when final HttpAsdcResponse response = HttpAsdcClient.createHttpResponse(httpStatusCode, httpMessage); // then - Assert.assertEquals(httpStatusCode, response.getStatus()); - Assert.assertEquals(httpMessage, getResponseMessage(response)); + assertEquals(httpStatusCode, response.getStatus()); + assertEquals(httpMessage, getResponseMessage(response)); } private String getResponseMessage(HttpAsdcResponse response) throws IOException { 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 4e74080..2dcfd5d 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 @@ -19,32 +19,31 @@ */ package org.onap.sdc.http; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.HashMap; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.message.BasicHeader; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.sdc.utils.Pair; import org.onap.sdc.utils.TestConfiguration; -import java.io.IOException; -import java.util.HashMap; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -@RunWith(MockitoJUnitRunner.class) -public class HttpAsdcClientTest { +@ExtendWith(MockitoExtension.class) +class HttpAsdcClientTest { private static final String URL = "http://127.0.0.1:8080/target"; private static final int HTTP_OK = 200; @@ -63,19 +62,19 @@ public class HttpAsdcClientTest { private HttpEntity httpEntity; @Test - public void shouldCreateInitializedHttpClient() { + void shouldCreateInitializedHttpClient() { // given TestConfiguration configuration = new TestConfiguration(); configuration.setUseHttpsWithSDC(false); // when final HttpRequestFactory httpRequestFactory = new HttpRequestFactory( - configuration.getUser(), - configuration.getPassword()); + configuration.getUser(), + configuration.getPassword()); final HttpAsdcClient httpAsdcClient = new HttpAsdcClient( - configuration.getAsdcAddress(), - new HttpClientFactory(configuration), - httpRequestFactory); + configuration.getAsdcAddress(), + new HttpClientFactory(configuration), + httpRequestFactory); // then assertNotNull(httpAsdcClient); @@ -83,19 +82,19 @@ public class HttpAsdcClientTest { } @Test - public void shouldCreateInitializedHttpsClient() { + void shouldCreateInitializedHttpsClient() { // given TestConfiguration configuration = new TestConfiguration(); configuration.setUseHttpsWithSDC(true); // when final HttpRequestFactory httpRequestFactory = new HttpRequestFactory( - configuration.getUser(), - configuration.getPassword()); + configuration.getUser(), + configuration.getPassword()); final HttpAsdcClient httpAsdcClient = new HttpAsdcClient( - configuration.getAsdcAddress(), - new HttpClientFactory(configuration), - httpRequestFactory); + configuration.getAsdcAddress(), + new HttpClientFactory(configuration), + httpRequestFactory); // then assertNotNull(httpAsdcClient); @@ -103,11 +102,11 @@ public class HttpAsdcClientTest { } @Test - public void shouldSendGetRequestWithoutAnyError() throws IOException { + void shouldSendGetRequestWithoutAnyError() throws IOException { // given TestConfiguration configuration = givenHttpConfiguration(); final HttpAsdcClient httpAsdcClient = createTestObj(HttpClientFactory.HTTP, configuration, httpClient); - CloseableHttpResponse httpResponse = givenHttpResponse(); + CloseableHttpResponse httpResponse = givenHttpResponse(true); // when final HttpAsdcResponse response = httpAsdcClient.getRequest(URL, HEADERS_MAP); @@ -125,14 +124,14 @@ public class HttpAsdcClientTest { } @Test - public void shouldSendPostRequestWithoutAnyError() throws IOException { + void shouldSendPostRequestWithoutAnyError() throws IOException { // given TestConfiguration configuration = givenHttpConfiguration(); final HttpAsdcClient httpAsdcClient = createTestObj(HttpClientFactory.HTTP, configuration, httpClient); - CloseableHttpResponse httpResponse = givenHttpResponse(); + CloseableHttpResponse httpResponse = givenHttpResponse(false); // when - final HttpAsdcResponse response = httpAsdcClient.postRequest(URL,httpEntity, HEADERS_MAP); + final HttpAsdcResponse response = httpAsdcClient.postRequest(URL, httpEntity, HEADERS_MAP); // then assertThat(response).isNotNull(); @@ -144,23 +143,25 @@ public class HttpAsdcClientTest { private HttpAsdcClient createTestObj(String httpProtocol, TestConfiguration configuration, CloseableHttpClient httpClient) { final HttpRequestFactory httpRequestFactory = new HttpRequestFactory( - configuration.getUser(), - configuration.getPassword()); + configuration.getUser(), + configuration.getPassword()); HttpClientFactory httpClientFactory = mock(HttpClientFactory.class); when(httpClientFactory.createInstance()).thenReturn(new Pair<>(httpProtocol, httpClient)); final HttpAsdcClient httpAsdcClient = new HttpAsdcClient( - configuration.getAsdcAddress(), - httpClientFactory, - httpRequestFactory); + configuration.getAsdcAddress(), + httpClientFactory, + httpRequestFactory); return httpAsdcClient; } - private CloseableHttpResponse givenHttpResponse(HttpEntity httpEntity, Header[] headers) { + private CloseableHttpResponse givenHttpResponse(HttpEntity httpEntity, Header[] headers, boolean includeGetAllHeaders) { CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class); StatusLine statusLine = mock(StatusLine.class); when(statusLine.getStatusCode()).thenReturn(HTTP_OK); when(httpResponse.getStatusLine()).thenReturn(statusLine); - when(httpResponse.getAllHeaders()).thenReturn(headers); + if (includeGetAllHeaders) { + when(httpResponse.getAllHeaders()).thenReturn(headers); + } when(httpResponse.getEntity()).thenReturn(httpEntity); return httpResponse; } @@ -171,8 +172,8 @@ public class HttpAsdcClientTest { return configuration; } - private CloseableHttpResponse givenHttpResponse() throws IOException { - CloseableHttpResponse httpResponse = givenHttpResponse(httpEntity, HEADERS); + private CloseableHttpResponse givenHttpResponse(boolean includeGetAllHeaders) throws IOException { + CloseableHttpResponse httpResponse = givenHttpResponse(httpEntity, HEADERS, includeGetAllHeaders); when(httpClient.execute(any())).thenReturn(httpResponse); return httpResponse; } 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 4594fb9..347b7f5 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 @@ -19,68 +19,68 @@ */ 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.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + import org.apache.http.client.CredentialsProvider; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.sdc.utils.Pair; import org.onap.sdc.utils.TestConfiguration; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - - -public class HttpClientFactoryTest { +class HttpClientFactoryTest { @Test - public void shouldReturnSSLConnection(){ + void shouldReturnSSLConnection() { 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.getKeyStorePassword()).thenReturn("Aa123456"); - Pair<String, CloseableHttpClient> client = httpClientFactory.createInstance(); + Pair<String, CloseableHttpClient> client = httpClientFactory.createInstance(); SSLConnectionSocketFactory sslsf = spy(SSLConnectionSocketFactory.getSocketFactory()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); CloseableHttpClient expectedHttpClient = HttpClientBuilder.create(). - setDefaultCredentialsProvider(credsProvider). - setSSLSocketFactory(sslsf). - build(); + setDefaultCredentialsProvider(credsProvider). + setSSLSocketFactory(sslsf). + build(); Pair<String, CloseableHttpClient> expectedClient = new Pair<>("https://", expectedHttpClient); assertNotNull(client); assertEquals(expectedClient.getFirst(), client.getFirst()); } @Test - public void shouldReturnSSLConnectionWithHttp(){ + void shouldReturnSSLConnectionWithHttp() { TestConfiguration config = spy(new TestConfiguration()); HttpClientFactory httpClientFactory = new HttpClientFactory(config); when(config.activateServerTLSAuth()).thenReturn(false); when(config.isUseHttpsWithSDC()).thenReturn(false); - Pair<String, CloseableHttpClient> client = httpClientFactory.createInstance(); + Pair<String, CloseableHttpClient> client = httpClientFactory.createInstance(); SSLConnectionSocketFactory sslsf = spy(SSLConnectionSocketFactory.getSocketFactory()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); CloseableHttpClient expectedHttpClient = HttpClientBuilder.create(). - setDefaultCredentialsProvider(credsProvider). - setSSLSocketFactory(sslsf). - build(); + setDefaultCredentialsProvider(credsProvider). + setSSLSocketFactory(sslsf). + build(); Pair<String, CloseableHttpClient> expectedClient = new Pair<>("http://", expectedHttpClient); assertNotNull(client); assertEquals(expectedClient.getFirst(), client.getFirst()); } - @Test (expected = HttpAsdcClientException.class) - public void shouldReturnSSLConnectionError() throws HttpAsdcClientException{ + @Test + void shouldReturnSSLConnectionError() throws HttpAsdcClientException { 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"); - httpClientFactory.createInstance(); + assertThrows(HttpAsdcClientException.class, () -> httpClientFactory.createInstance()); } -}
\ No newline at end of file +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpRequestFactoryTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpRequestFactoryTest.java index ba42703..c9eb4b3 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpRequestFactoryTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/http/HttpRequestFactoryTest.java @@ -20,20 +20,19 @@ package org.onap.sdc.http; -import org.apache.http.HttpEntity; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.junit.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class HttpRequestFactoryTest { +class HttpRequestFactoryTest { private static final String URL = "https://127.0.0.1:8080/target"; private static final String EXPECTED_AUTHORIZATION_VALUE = "Basic dXNlcjpwYXNzd29yZA=="; @@ -41,7 +40,7 @@ public class HttpRequestFactoryTest { private static final String HEADER_KEY_2 = "key2"; private static final String HEADER_VALUE_1 = "value1"; private static final String HEADER_VALUE_2 = "value2"; - private static final Map<String, String> HEADERS = new HashMap<String, String>(){ + private static final Map<String, String> HEADERS = new HashMap<String, String>() { { put(HEADER_KEY_1, HEADER_VALUE_1); put(HEADER_KEY_2, HEADER_VALUE_2); @@ -51,22 +50,22 @@ public class HttpRequestFactoryTest { private HttpRequestFactory testObj = new HttpRequestFactory("user", "password"); @Test - public void shouldCreateValidGetHttpRequest() throws URISyntaxException { + void shouldCreateValidGetHttpRequest() throws URISyntaxException { // when final HttpGet httpGetRequest = testObj.createHttpGetRequest(URL, HEADERS); // then assertThat(httpGetRequest.getURI()).isEqualTo(new URI(URL)); assertThat(httpGetRequest.getFirstHeader(HEADER_KEY_1).getValue()) - .isEqualTo(HEADER_VALUE_1); + .isEqualTo(HEADER_VALUE_1); assertThat(httpGetRequest.getFirstHeader(HEADER_KEY_2).getValue()) - .isEqualTo(HEADER_VALUE_2); + .isEqualTo(HEADER_VALUE_2); assertThat(httpGetRequest.getFirstHeader(HttpRequestFactory.AUTHORIZATION).getValue()) - .isEqualTo(EXPECTED_AUTHORIZATION_VALUE); + .isEqualTo(EXPECTED_AUTHORIZATION_VALUE); } @Test - public void shouldCreateValidPostHttpRequest() throws URISyntaxException { + void shouldCreateValidPostHttpRequest() throws URISyntaxException { // given final HttpEntity httpEntity = mock(HttpEntity.class); @@ -77,10 +76,10 @@ public class HttpRequestFactoryTest { assertThat(httpPostRequest.getURI()).isEqualTo(new URI(URL)); assertThat(httpPostRequest.getEntity()).isEqualTo(httpEntity); assertThat(httpPostRequest.getFirstHeader(HEADER_KEY_1).getValue()) - .isEqualTo(HEADER_VALUE_1); + .isEqualTo(HEADER_VALUE_1); assertThat(httpPostRequest.getFirstHeader(HEADER_KEY_2).getValue()) - .isEqualTo(HEADER_VALUE_2); + .isEqualTo(HEADER_VALUE_2); assertThat(httpPostRequest.getFirstHeader(HttpRequestFactory.AUTHORIZATION).getValue()) - .isEqualTo(EXPECTED_AUTHORIZATION_VALUE); + .isEqualTo(EXPECTED_AUTHORIZATION_VALUE); } } 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 6ff0f9b..b09de78 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 @@ -21,20 +21,25 @@ package org.onap.sdc.http; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.any; +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.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; +import fj.data.Either; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -43,59 +48,48 @@ 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.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Matchers; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; 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.api.asdc.RegistrationRequest; -import org.onap.sdc.api.consumer.IConfiguration; import org.onap.sdc.utils.DistributionActionResultEnum; import org.onap.sdc.utils.Pair; -import com.att.nsa.apiClient.credentials.ApiCredential; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import fj.data.Either; - -public class SdcConnectorClientTest { +class SdcConnectorClientTest { - private static Gson gson = new GsonBuilder().create(); 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); + 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 SdcConnectorClient asdcClient; - - 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 String VALID_JSON_PAYLOAD = gson.toJson(ARTIFACT_TYPES); - private static final int PORT = 49512; - private static final byte[] BYTES = new byte[] {0xA, 0xB, 0xC, 0xD}; - - - @BeforeClass + @BeforeAll public static void beforeClass() { asdcClient = Mockito.spy(new SdcConnectorClient(configuration, httpClient)); when(apiCredential.getApiKey()).thenReturn(MOCK_API_KEY); @@ -105,25 +99,23 @@ public class SdcConnectorClientTest { doReturn(mockResponse).when(asdcClient).parseRegistrationResponse(httpAsdcResponse); } - @Before + @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(Mockito.eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), Mockito.any(HttpEntity.class), - Mockito.eq(mockHeaders), Mockito.eq(false)); + }).when(httpClient).postRequest(eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), any(HttpEntity.class), eq(mockHeaders), eq(false)); } - @Test(expected = IllegalStateException.class) - public void initAndCloseTest() { + @Test + void initAndCloseTest() { IConfiguration conf = Mockito.mock(IConfiguration.class); when(conf.getUser()).thenReturn("user"); when(conf.getPassword()).thenReturn("password"); @@ -134,56 +126,51 @@ public class SdcConnectorClientTest { SdcConnectorClient client = new SdcConnectorClient(conf, httpClient); client.close(); - //check if client is really closed - httpClient.getRequest(AsdcUrls.POST_FOR_TOPIC_REGISTRATION, new HashMap<>()); + assertThrows(IllegalStateException.class, () -> { + //check if client is really closed + httpClient.getRequest(AsdcUrls.POST_FOR_TOPIC_REGISTRATION, new HashMap<>()); + }); + } @Test - public void testConsumeProduceStatusTopicFalse() throws UnsupportedOperationException, IOException { - + void testConsumeProduceStatusTopicFalse() throws UnsupportedOperationException, IOException { testConsumeProduceStatusTopic(false); - } @Test - public void testConsumeProduceStatusTopicTrue() throws UnsupportedOperationException, IOException { - + void testConsumeProduceStatusTopicTrue() throws UnsupportedOperationException, IOException { testConsumeProduceStatusTopic(true); - } private void testConsumeProduceStatusTopic(final boolean isConsumeProduceStatusFlag) throws IOException { when(configuration.isConsumeProduceStatusTopic()).thenReturn(isConsumeProduceStatusFlag); asdcClient.registerAsdcTopics(apiCredential); - verify(httpClient, times(1)) - .postRequest(Mockito.eq(AsdcUrls.POST_FOR_TOPIC_REGISTRATION), any(HttpEntity.class), - Mockito.eq(mockHeaders), Mockito.eq(false)); + 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); - - assertTrue(actualRegRequest.getApiPublicKey().equals(expectedRegRequest.getApiPublicKey())); - assertTrue(actualRegRequest.getDistrEnvName().equals(expectedRegRequest.getDistrEnvName())); - assertTrue(actualRegRequest.getIsConsumerToSdcDistrStatusTopic() - .equals(expectedRegRequest.getIsConsumerToSdcDistrStatusTopic())); + 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()); } @Test - public void getValidArtifactTypesListHappyScenarioTest() throws IOException { + void getValidArtifactTypesListHappyScenarioTest() throws IOException { HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); CloseableHttpResponse closeableHttpResponseMock = mock(CloseableHttpResponse.class); HttpEntity messageMock = mock(HttpEntity.class); Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = - new Pair<>(responseMock, closeableHttpResponseMock); + 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), Matchers.any(), eq(false))) - .thenReturn(responsePair); + when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + .thenReturn(responsePair); Either<List<String>, IDistributionClientResult> result = asdcClient.getValidArtifactTypesList(); assertTrue(result.isLeft()); @@ -192,7 +179,7 @@ public class SdcConnectorClientTest { } @Test - public void getValidArtifactTypesListErrorResponseScenarioTest() throws IOException { + void getValidArtifactTypesListErrorResponseScenarioTest() throws IOException { HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); HttpEntity messageMock = mock(HttpEntity.class); Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = new Pair<>(responseMock, null); @@ -200,30 +187,30 @@ public class SdcConnectorClientTest { 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), Matchers.any(), eq(false))) - .thenReturn(responsePair); + when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + .thenReturn(responsePair); Either<List<String>, IDistributionClientResult> result = asdcClient.getValidArtifactTypesList(); assertTrue(result.isRight()); IDistributionClientResult distributionClientResult = result.right().value(); assertEquals(DistributionActionResultEnum.ASDC_SERVER_TIMEOUT, - distributionClientResult.getDistributionActionResult()); + distributionClientResult.getDistributionActionResult()); } @Test - public void getValidArtifactTypesListExceptionDuringConnectionClosingTest() throws IOException { + void getValidArtifactTypesListExceptionDuringConnectionClosingTest() throws IOException { HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); CloseableHttpResponse closeableHttpResponseMock = mock(CloseableHttpResponse.class); HttpEntity messageMock = mock(HttpEntity.class); Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = - new Pair<>(responseMock, closeableHttpResponseMock); + 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), Matchers.any(), eq(false))) - .thenReturn(responsePair); + when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + .thenReturn(responsePair); doThrow(new IOException("Test exception")).when(closeableHttpResponseMock).close(); @@ -231,36 +218,36 @@ public class SdcConnectorClientTest { assertTrue(result.isRight()); IDistributionClientResult distributionClientResult = result.right().value(); assertEquals(DistributionActionResultEnum.ASDC_SERVER_TIMEOUT, - distributionClientResult.getDistributionActionResult()); + distributionClientResult.getDistributionActionResult()); } @Test - public void getValidArtifactTypesListParsingExceptionHandlingTest() throws IOException { + void getValidArtifactTypesListParsingExceptionHandlingTest() throws IOException { HttpAsdcResponse responseMock = mock(HttpAsdcResponse.class); CloseableHttpResponse closeableHttpResponseMock = mock(CloseableHttpResponse.class); HttpEntity messageMock = mock(HttpEntity.class); Pair<HttpAsdcResponse, CloseableHttpResponse> responsePair = - new Pair<>(responseMock, closeableHttpResponseMock); + 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), Matchers.any(), eq(false))) - .thenReturn(responsePair); + when(httpClient.getRequest(eq(AsdcUrls.GET_VALID_ARTIFACT_TYPES), any(), eq(false))) + .thenReturn(responsePair); Either<List<String>, IDistributionClientResult> result = asdcClient.getValidArtifactTypesList(); assertTrue(result.isRight()); IDistributionClientResult distributionClientResult = result.right().value(); assertEquals(DistributionActionResultEnum.GENERAL_ERROR, - distributionClientResult.getDistributionActionResult()); + distributionClientResult.getDistributionActionResult()); } @Test - public void unregisterTopicsErrorDuringProcessingTest() throws IOException { + 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")); + .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); @@ -271,14 +258,14 @@ public class SdcConnectorClientTest { 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)); + .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 - public void unregisterTopicsHappyScenarioTest() throws IOException { + void unregisterTopicsHappyScenarioTest() throws IOException { when(configuration.getAsdcAddress()).thenReturn("127.0.0.1" + PORT); when(configuration.isConsumeProduceStatusTopic()).thenReturn(false); @@ -291,14 +278,14 @@ public class SdcConnectorClientTest { 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)); + .postRequest(eq(AsdcUrls.POST_FOR_UNREGISTER), any(HttpEntity.class), any(), eq(false)); IDistributionClientResult result = asdcClient.unregisterTopics(apiCredential); assertEquals(DistributionActionResultEnum.SUCCESS, result.getDistributionActionResult()); } @Test - public void downloadArtifactHappyScenarioTest() throws IOException { + void downloadArtifactHappyScenarioTest() throws IOException { Map<String, String> headers = new HashMap<>(); headers.put(asdcClient.CONTENT_DISPOSITION_HEADER, "SomeHeader"); @@ -321,7 +308,7 @@ public class SdcConnectorClientTest { } @Test - public void downloadArtifactDataIntegrityProblemTest() throws IOException { + void downloadArtifactDataIntegrityProblemTest() throws IOException { IArtifactInfo artifactInfo = mock(IArtifactInfo.class); when(artifactInfo.getArtifactURL()).thenReturn(ARTIFACT_URL); @@ -339,7 +326,7 @@ public class SdcConnectorClientTest { } @Test - public void downloadArtifactExceptionDuringDownloadHandlingTest() throws IOException { + void downloadArtifactExceptionDuringDownloadHandlingTest() throws IOException { IArtifactInfo artifactInfo = mock(IArtifactInfo.class); when(artifactInfo.getArtifactURL()).thenReturn(ARTIFACT_URL); @@ -357,7 +344,7 @@ public class SdcConnectorClientTest { } @Test - public void downloadArtifactHandleDownloadErrorTest() throws IOException { + void downloadArtifactHandleDownloadErrorTest() throws IOException { IArtifactInfo artifactInfo = mock(IArtifactInfo.class); when(artifactInfo.getArtifactURL()).thenReturn(ARTIFACT_URL); @@ -376,8 +363,8 @@ public class SdcConnectorClientTest { private String excpectedStringBody(boolean isConsumeProduceStatusTopic) { String stringBodyTemplate = - "{\r\n" + " \"apiPublicKey\": \"MockApikey\",\r\n" + " \"distrEnvName\": \"MockEnv\",\r\n" - + " \"isConsumerToSdcDistrStatusTopic\": %s\r\n" + "}"; + "{\r\n" + " \"apiPublicKey\": \"MockApikey\",\r\n" + " \"distrEnvName\": \"MockEnv\",\r\n" + + " \"isConsumerToSdcDistrStatusTopic\": %s\r\n" + "}"; return String.format(stringBodyTemplate, isConsumeProduceStatusTopic); } diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/ConfigurationValidatorTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/ConfigurationValidatorTest.java index fca3aee..1b8a556 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/ConfigurationValidatorTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/ConfigurationValidatorTest.java @@ -20,40 +20,42 @@ */ package org.onap.sdc.impl; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +class ConfigurationValidatorTest { -public class ConfigurationValidatorTest { - private static final String[] VALID_FQDNS = {"myHostname", "myHostname:80", "myHostname:8080", "1.1.1.1", "1.1.1.1:8080", "ueb01hydc.it.open.com", "ueb01hydc.it.open.com:8080", "ueb01hydc.it", "my-good.and-simple.fqdn"}; - private static final String[] INVALID_FQDNS = {"myHostname:808080", /* 70 letters */"abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", "not**good", "very#not#good#"}; + private static final String[] VALID_FQDNS = {"myHostname", "myHostname:80", "myHostname:8080", "1.1.1.1", "1.1.1.1:8080", "ueb01hydc.it.open.com", + "ueb01hydc.it.open.com:8080", "ueb01hydc.it", "my-good.and-simple.fqdn"}; + private static final String[] INVALID_FQDNS = {"myHostname:808080", /* 70 letters */ + "abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", "not**good", "very#not#good#"}; @Test - public void shouldReportThatFqdnIsValid() { + void shouldReportThatFqdnIsValid() { for (String validFqdn : VALID_FQDNS) { boolean validationResult = ConfigurationValidator.isValidFqdn(validFqdn); - assertEquals("assertion failed for FQDN " + validFqdn + " expected to be valid, actual invalid", true, validationResult); + assertTrue(validationResult, "assertion failed for FQDN " + validFqdn + " expected to be valid, actual invalid"); } } @Test - public void shouldReportThatFqdnIsInvalid() { + void shouldReportThatFqdnIsInvalid() { for (String invalidFqdn : INVALID_FQDNS) { boolean validationResult = ConfigurationValidator.isValidFqdn(invalidFqdn); - assertEquals("assertion failed for FQDN " + invalidFqdn + " expected to be invalid, actual valid", false, validationResult); + assertFalse(validationResult, "assertion failed for FQDN " + invalidFqdn + " expected to be invalid, actual valid"); } } + @Test - public void shouldReportThatFqdnsAreValid() { + void shouldReportThatFqdnsAreValid() { assertTrue(ConfigurationValidator.isValidFqdns(Arrays.asList(VALID_FQDNS))); } @Test - public void shouldReportThatFqdnsAreInvalid() { + void shouldReportThatFqdnsAreInvalid() { assertFalse(ConfigurationValidator.isValidFqdns(Arrays.asList(INVALID_FQDNS))); } } diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java index 82f77d8..8b7a897 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionClientDownloadResultTest.java @@ -7,9 +7,9 @@ * 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. @@ -20,56 +20,55 @@ package org.onap.sdc.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.onap.sdc.utils.DistributionActionResultEnum; +class DistributionClientDownloadResultTest { -public class DistributionClientDownloadResultTest { - - public static DistributionClientDownloadResultImpl distributionClientDownloadResult; - - @BeforeClass - public static void init(){ - distributionClientDownloadResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, ""); - } - - @Test - public void testNonHeaderFilename(){ - distributionClientDownloadResult.setArtifactName("service-BkPerformanceSrvs-csar.csar"); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testNullFilename(){ - distributionClientDownloadResult.setArtifactName(null); - assertNull(distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameFromHeaderNoSpace(){ - distributionClientDownloadResult.setArtifactName("attachment;filename=\"service-BkPerformanceSrvs-csar.csar\""); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameFromHeaderOneSpace(){ - distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameFromHeaderManySpaces(){ - distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); - assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); - } - - @Test - public void testFilenameEmpty(){ - distributionClientDownloadResult.setArtifactName("attachment; filename=\"\""); - assertEquals("", distributionClientDownloadResult.getArtifactFilename()); - } + public static DistributionClientDownloadResultImpl distributionClientDownloadResult; + + @BeforeAll + public static void init() { + distributionClientDownloadResult = new DistributionClientDownloadResultImpl(DistributionActionResultEnum.SUCCESS, ""); + } + + @Test + void testNonHeaderFilename() { + distributionClientDownloadResult.setArtifactName("service-BkPerformanceSrvs-csar.csar"); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + void testNullFilename() { + distributionClientDownloadResult.setArtifactName(null); + assertNull(distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + void testFilenameFromHeaderNoSpace() { + distributionClientDownloadResult.setArtifactName("attachment;filename=\"service-BkPerformanceSrvs-csar.csar\""); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + void testFilenameFromHeaderOneSpace() { + distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + void testFilenameFromHeaderManySpaces() { + distributionClientDownloadResult.setArtifactName("attachment; filename=\"service-BkPerformanceSrvs-csar.csar\""); + assertEquals("service-BkPerformanceSrvs-csar.csar", distributionClientDownloadResult.getArtifactFilename()); + } + + @Test + void testFilenameEmpty() { + distributionClientDownloadResult.setArtifactName("attachment; filename=\"\""); + assertEquals("", distributionClientDownloadResult.getArtifactFilename()); + } } 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 d5c8ff6..0297918 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 @@ -21,503 +21,506 @@ package org.onap.sdc.impl; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doReturn; +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.List; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.onap.sdc.http.HttpAsdcClient; -import org.onap.sdc.utils.Pair; -import org.onap.sdc.utils.TestConfiguration; 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.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; +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 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; - -public class DistributionClientTest { - - static CambriaIdentityManager cc; - DistributionClientImpl client = Mockito.spy(new DistributionClientImpl()); - IConfiguration testConfiguration = new TestConfiguration(); - SdcConnectorClient connector = Mockito.mock(SdcConnectorClient.class); - - - @After - public void afterTest() { - client.stop(); - } - - @Test - public void validateConfigurationTest() { - final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration(new Wrapper<IDistributionClientResult>(), testConfiguration); - DistributionActionResultEnum validationResult = distributionActionResultEnumConfigurationPair.getFirst(); - Configuration configuration = distributionActionResultEnumConfigurationPair.getSecond(); - Assert.assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); - Assert.assertEquals(testConfiguration.getPollingInterval(), configuration.getPollingInterval()); - Assert.assertEquals(testConfiguration.getPollingTimeout(), configuration.getPollingTimeout()); - } - - @Test - public void validateConfigurationToDefaultTest() { - TestConfiguration userConfig = new TestConfiguration(); - userConfig.setPollingInterval(1); - userConfig.setPollingTimeout(2); - final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration(new Wrapper<IDistributionClientResult>(), userConfig); - DistributionActionResultEnum validationResult = distributionActionResultEnumConfigurationPair.getFirst(); - Configuration configuration = distributionActionResultEnumConfigurationPair.getSecond(); - Assert.assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); - assertEquals(15, configuration.getPollingInterval()); - assertEquals(15, configuration.getPollingTimeout()); - } - - @Test - public void validateConfigurationPasswordTest() { - Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>(); - TestConfiguration testPassword = new TestConfiguration(); - testPassword.setPassword(null); - DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword).getFirst(); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); - - testPassword.setPassword(""); - validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword).getFirst(); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); - - } - - @Test - public void validateConfigurationUserTest() { - Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>(); - TestConfiguration testUser = new TestConfiguration(); - testUser.setUser(null); - DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testUser).getFirst(); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); - - testUser.setUser(""); - validationResult = client.validateAndInitConfiguration(errorWrapper, testUser).getFirst(); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); - - } - - @Test - public 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; - - // no password - TestConfiguration testPassword = new TestConfiguration(); - testPassword.setPassword(null); - IDistributionClientResult validationResult = client.init(testPassword, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); - - testPassword.setPassword(""); - validationResult = client.init(testPassword, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); - - // no username - TestConfiguration testUser = new TestConfiguration(); - testUser.setUser(null); - validationResult = client.init(testUser, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); - - testUser.setUser(""); - validationResult = client.init(testUser, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); - - // no ASDC server fqdn - TestConfiguration testServerFqdn = new TestConfiguration(); - testServerFqdn.setAsdcAddress(null); - validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); - - testServerFqdn.setAsdcAddress(""); - validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); - - testServerFqdn.setAsdcAddress("this##is##bad##fqdn"); - validationResult = client.init(testServerFqdn, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN, validationResult.getDistributionActionResult()); - - // no consumerId - TestConfiguration testConsumerId = new TestConfiguration(); - testConsumerId.setComsumerID(null); - validationResult = client.init(testConsumerId, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); - - testConsumerId.setComsumerID(""); - validationResult = client.init(testConsumerId, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); - - // no environmentName - TestConfiguration testEnv = new TestConfiguration(); - testEnv.setEnvironmentName(null); - validationResult = client.init(testEnv, new TestNotificationCallback()); - Assert.assertEquals(DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME, validationResult.getDistributionActionResult()); - - testEnv.setEnvironmentName(""); - validationResult = client.init(testEnv, new TestNotificationCallback()); - Assert.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()); - } - - @Test - public 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; - - TestConfiguration badAsdcConfig = new TestConfiguration(); - if (badAsdcConfig.isUseHttpsWithSDC() == null) { - System.out.println("null for HTTPS then TRUE"); - } else { - System.out.println("isUseHttpsWithSDC set to " + badAsdcConfig.isUseHttpsWithSDC()); - } - badAsdcConfig.setAsdcAddress("badhost:8080"); - - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); - - badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("localhost:8181"); - - init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); - - } - - @Test - public void initFailedConnectAsdcInHttpTest() 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; - - TestConfiguration badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("badhost:8080"); - badAsdcConfig.setUseHttpsWithSDC(false); - - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); - - badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setAsdcAddress("localhost:8181"); - badAsdcConfig.setUseHttpsWithSDC(false); - - init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); - - } - - @Test - public void getConfigurationTest() 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); - IDistributionClientResult success = initSuccesResult(); - Mockito.when(connector.unregisterTopics(Mockito.any(ApiCredential.class))).thenReturn(success); +class DistributionClientTest { + + static CambriaIdentityManager cc; + DistributionClientImpl client = Mockito.spy(new DistributionClientImpl()); + IConfiguration testConfiguration = new TestConfiguration(); + SdcConnectorClient connector = Mockito.mock(SdcConnectorClient.class); + + + @AfterEach + public void afterTest() { + client.stop(); + } + + @Test + void validateConfigurationTest() { + final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration( + new Wrapper<IDistributionClientResult>(), testConfiguration); + DistributionActionResultEnum validationResult = distributionActionResultEnumConfigurationPair.getFirst(); + Configuration configuration = distributionActionResultEnumConfigurationPair.getSecond(); + assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); + assertEquals(testConfiguration.getPollingInterval(), configuration.getPollingInterval()); + assertEquals(testConfiguration.getPollingTimeout(), configuration.getPollingTimeout()); + } + + @Test + void validateConfigurationToDefaultTest() { + TestConfiguration userConfig = new TestConfiguration(); + userConfig.setPollingInterval(1); + userConfig.setPollingTimeout(2); + final Pair<DistributionActionResultEnum, Configuration> distributionActionResultEnumConfigurationPair = client.validateAndInitConfiguration( + new Wrapper<>(), userConfig); + DistributionActionResultEnum validationResult = distributionActionResultEnumConfigurationPair.getFirst(); + Configuration configuration = distributionActionResultEnumConfigurationPair.getSecond(); + assertEquals(DistributionActionResultEnum.SUCCESS, validationResult); + assertEquals(15, configuration.getPollingInterval()); + assertEquals(15, configuration.getPollingTimeout()); + } + + @Test + void validateConfigurationPasswordTest() { + Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>(); + TestConfiguration testPassword = new TestConfiguration(); + testPassword.setPassword(null); + DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword).getFirst(); + assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); + + testPassword.setPassword(""); + validationResult = client.validateAndInitConfiguration(errorWrapper, testPassword).getFirst(); + assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult); + + } + + @Test + void validateConfigurationUserTest() { + Wrapper<IDistributionClientResult> errorWrapper = new Wrapper<>(); + TestConfiguration testUser = new TestConfiguration(); + testUser.setUser(null); + DistributionActionResultEnum validationResult = client.validateAndInitConfiguration(errorWrapper, testUser).getFirst(); + assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); + + testUser.setUser(""); + validationResult = client.validateAndInitConfiguration(errorWrapper, testUser).getFirst(); + assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult); + + } + + @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; + + // no password + TestConfiguration testPassword = new TestConfiguration(); + testPassword.setPassword(null); + IDistributionClientResult validationResult = client.init(testPassword, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); + + testPassword.setPassword(""); + validationResult = client.init(testPassword, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_PASSWORD, validationResult.getDistributionActionResult()); + + // no username + TestConfiguration testUser = new TestConfiguration(); + testUser.setUser(null); + validationResult = client.init(testUser, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); + + testUser.setUser(""); + validationResult = client.init(testUser, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_USERNAME, validationResult.getDistributionActionResult()); + + // no ASDC server fqdn + TestConfiguration testServerFqdn = new TestConfiguration(); + testServerFqdn.setAsdcAddress(null); + validationResult = client.init(testServerFqdn, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); + + testServerFqdn.setAsdcAddress(""); + validationResult = client.init(testServerFqdn, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_ASDC_FQDN, validationResult.getDistributionActionResult()); + + testServerFqdn.setAsdcAddress("this##is##bad##fqdn"); + validationResult = client.init(testServerFqdn, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_INVALID_ASDC_FQDN, validationResult.getDistributionActionResult()); + + // no consumerId + TestConfiguration testConsumerId = new TestConfiguration(); + testConsumerId.setComsumerID(null); + validationResult = client.init(testConsumerId, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); + + testConsumerId.setComsumerID(""); + validationResult = client.init(testConsumerId, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_CONSUMER_ID, validationResult.getDistributionActionResult()); + + // no environmentName + TestConfiguration testEnv = new TestConfiguration(); + testEnv.setEnvironmentName(null); + validationResult = client.init(testEnv, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.CONF_MISSING_ENVIRONMENT_NAME, validationResult.getDistributionActionResult()); + + testEnv.setEnvironmentName(""); + 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()); + } + + @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; + + TestConfiguration badAsdcConfig = new TestConfiguration(); + if (badAsdcConfig.isUseHttpsWithSDC() == null) { + System.out.println("null for HTTPS then TRUE"); + } else { + System.out.println("isUseHttpsWithSDC set to " + badAsdcConfig.isUseHttpsWithSDC()); + } + badAsdcConfig.setAsdcAddress("badhost:8080"); - reconfigureAsdcConnector(connector, client); + IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + + badAsdcConfig = new TestConfiguration(); + badAsdcConfig.setAsdcAddress("localhost:8181"); + + init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + + } + + @Test + void initFailedConnectAsdcInHttpTest() 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; + + TestConfiguration badAsdcConfig = new TestConfiguration(); + badAsdcConfig.setAsdcAddress("badhost:8080"); + badAsdcConfig.setUseHttpsWithSDC(false); + + IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + + badAsdcConfig = new TestConfiguration(); + badAsdcConfig.setAsdcAddress("localhost:8181"); + badAsdcConfig.setUseHttpsWithSDC(false); + + init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.ASDC_CONNECTION_FAILED, init.getDistributionActionResult()); + + } + + @Test + void getConfigurationTest() 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); + 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; + + TestConfiguration badAsdcConfig = new TestConfiguration(); + badAsdcConfig.setPollingInterval(-5); + + IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); + + String confString = client.getConfiguration().toString(); + System.out.println(confString); + + } + + private IDistributionClientResult initSuccesResult() { + return new IDistributionClientResult() { + + @Override + public String getDistributionMessageResult() { + return "success"; + } + + @Override + public DistributionActionResultEnum getDistributionActionResult() { + return DistributionActionResultEnum.SUCCESS; + } + }; + } - // cambriaMock + @Test + void initWithMocksTest() throws HttpException, CambriaApiException, IOException { - 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; + mockArtifactTypeList(); - TestConfiguration badAsdcConfig = new TestConfiguration(); - badAsdcConfig.setPollingInterval(-5); + 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); - IDistributionClientResult init = client.init(badAsdcConfig, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); + reconfigureAsdcConnector(connector, client); - String confString = client.getConfiguration().toString(); - System.out.println(confString); + // cambriaMock - } - - private IDistributionClientResult initSuccesResult() { - return new IDistributionClientResult() { - - @Override - public String getDistributionMessageResult() { - return "success"; - } - - @Override - public DistributionActionResultEnum getDistributionActionResult() { - return DistributionActionResultEnum.SUCCESS; - } - }; - } - - @Test - public void initWithMocksTest() throws HttpException, CambriaApiException, IOException { - - 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; - - 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); - } - - private void mockArtifactTypeList() { - List<String> artifactTypes = new ArrayList<>(); - for (ArtifactTypeEnum artifactType : ArtifactTypeEnum.values()) { - artifactTypes.add(artifactType.name()); - } - - final Either<List<String>, IDistributionClientResult> eitherArtifactTypes = Either.left(artifactTypes); - Mockito.when(connector.getValidArtifactTypesList()).thenReturn(eitherArtifactTypes); - } - - @Test - public void testAlreadyInitTest() throws HttpException, CambriaApiException, IOException { - initWithMocksTest(); - IDistributionClientResult initResponse = client.init(testConfiguration, new TestNotificationCallback()); - assertEquals(DistributionActionResultEnum.DISTRIBUTION_CLIENT_ALREADY_INITIALIZED, initResponse.getDistributionActionResult()); - } - - @Test - public 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; - - 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); - } + 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; - @Test - public void initCreateKeysFailedTest() throws HttpException, CambriaApiException, IOException { + 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); + } - // connectorMock - mockArtifactTypeList(); + private void mockArtifactTypeList() { + List<String> artifactTypes = new ArrayList<>(); + for (ArtifactTypeEnum artifactType : ArtifactTypeEnum.values()) { + artifactTypes.add(artifactType.name()); + } - 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); + final Either<List<String>, IDistributionClientResult> eitherArtifactTypes = Either.left(artifactTypes); + 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()); + } + + @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); - reconfigureAsdcConnector(connector, client); + // cambriaMock - // 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.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); + } - 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; + @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; + } - 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 - public 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); - } - - @Test - public void testStartWithoutInit() { - IDistributionClientResult result = client.start(); - assertTrue(result.getDistributionActionResult() == DistributionActionResultEnum.DISTRIBUTION_CLIENT_NOT_INITIALIZED); - } - - 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 ########### + // ########### 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(); - Assert.assertEquals(DistributionActionResultEnum.SUCCESS, keysResult.getDistributionActionResult()); - Assert.assertFalse(client.credential.getApiKey().isEmpty()); - Assert.assertFalse(client.credential.getApiSecret().isEmpty()); + 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()); - - } - - @Test - public void testDecodeVfModuleArtifact() throws IOException{ - String vfModuleContent = getVFModuleExample(); - List<IVfModuleMetadata> decodeVfModuleArtifact = client.decodeVfModuleArtifact(vfModuleContent.getBytes()); - assertTrue(decodeVfModuleArtifact.size() == 1); - IVfModuleMetadata iVfModuleMetadata = decodeVfModuleArtifact.get(0); - assertTrue(iVfModuleMetadata.getArtifacts().size() == 11); - assertEquals(iVfModuleMetadata.getVfModuleModelName(), "Vccfdb..base_vDB_11032016..module-0"); - } + public void initTestCI() { + IDistributionClient distributionClient = DistributionClientFactory.createDistributionClient(); + IDistributionClientResult init = distributionClient.init(testConfiguration, new TestNotificationCallback()); + assertEquals(DistributionActionResultEnum.SUCCESS, init.getDistributionActionResult()); + + } + + @Test + void testDecodeVfModuleArtifact() throws IOException { + String vfModuleContent = getVFModuleExample(); + List<IVfModuleMetadata> decodeVfModuleArtifact = client.decodeVfModuleArtifact(vfModuleContent.getBytes()); + assertEquals(1, decodeVfModuleArtifact.size()); + IVfModuleMetadata iVfModuleMetadata = decodeVfModuleArtifact.get(0); + assertEquals(11, iVfModuleMetadata.getArtifacts().size()); + assertEquals("Vccfdb..base_vDB_11032016..module-0", iVfModuleMetadata.getVfModuleModelName()); + } private String getVFModuleExample() { - return "[\r\n" + - " {\r\n" + - " \"vfModuleModelName\": \"Vccfdb..base_vDB_11032016..module-0\",\r\n" + - " \"vfModuleModelInvariantUUID\": \"89bcc10e-84f9-475a-b7e3-bdac6cd2b31a\",\r\n" + - " \"vfModuleModelVersion\": \"1\",\r\n" + - " \"vfModuleModelUUID\": \"f7e1c7aa-cc7b-4dfc-b761-237e8063bd96\",\r\n" + - " \"GuguBubu\": true,\r\n" + - " \"isBase\": true,\r\n" + - " \"artifacts\": [\r\n" + - " \"68733000-7656-487c-aecb-040af96df5a5\",\r\n" + - " \"d3519bb4-be98-4c04-8815-4557379fdff3\",\r\n" + - " \"b445d84b-de23-4f0c-a0aa-8d794d85bebe\",\r\n" + - " \"52a6656a-63f4-4ae8-80f4-40febcaa15d6\",\r\n" + - " \"fdcf20b5-1bac-4da7-9e77-b0b565115027\",\r\n" + - " \"d3fcfd98-941c-4627-8b94-386dd3eab1ab\",\r\n" + - " \"bdd6c2b6-793b-49d7-8590-51e7d6998f69\",\r\n" + - " \"554a62b0-3a56-4c29-bc5e-23badf6da67f\",\r\n" + - " \"4b922d87-f2c9-44da-b933-57a91294fb42\",\r\n" + - " \"ad5cceda-0fa4-415e-b319-96f080e4b5c7\",\r\n" + - " \"8f4312f4-7be5-4d64-a3f5-564be7a0f01e\"\r\n" + - " ]\r\n" + - " }\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 ########### + return "[\r\n" + + " {\r\n" + + " \"vfModuleModelName\": \"Vccfdb..base_vDB_11032016..module-0\",\r\n" + + " \"vfModuleModelInvariantUUID\": \"89bcc10e-84f9-475a-b7e3-bdac6cd2b31a\",\r\n" + + " \"vfModuleModelVersion\": \"1\",\r\n" + + " \"vfModuleModelUUID\": \"f7e1c7aa-cc7b-4dfc-b761-237e8063bd96\",\r\n" + + " \"GuguBubu\": true,\r\n" + + " \"isBase\": true,\r\n" + + " \"artifacts\": [\r\n" + + " \"68733000-7656-487c-aecb-040af96df5a5\",\r\n" + + " \"d3519bb4-be98-4c04-8815-4557379fdff3\",\r\n" + + " \"b445d84b-de23-4f0c-a0aa-8d794d85bebe\",\r\n" + + " \"52a6656a-63f4-4ae8-80f4-40febcaa15d6\",\r\n" + + " \"fdcf20b5-1bac-4da7-9e77-b0b565115027\",\r\n" + + " \"d3fcfd98-941c-4627-8b94-386dd3eab1ab\",\r\n" + + " \"bdd6c2b6-793b-49d7-8590-51e7d6998f69\",\r\n" + + " \"554a62b0-3a56-4c29-bc5e-23badf6da67f\",\r\n" + + " \"4b922d87-f2c9-44da-b933-57a91294fb42\",\r\n" + + " \"ad5cceda-0fa4-415e-b319-96f080e4b5c7\",\r\n" + + " \"8f4312f4-7be5-4d64-a3f5-564be7a0f01e\"\r\n" + + " ]\r\n" + + " }\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/DistributionStatusMessageImplTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionStatusMessageImplTest.java index bf78a2a..e15e88d 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionStatusMessageImplTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/DistributionStatusMessageImplTest.java @@ -19,15 +19,15 @@ */ package org.onap.sdc.impl; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.onap.sdc.api.consumer.IComponentDoneStatusMessage; import org.onap.sdc.api.consumer.IDistributionStatusMessage; import org.onap.sdc.api.consumer.IFinalDistrStatusMessage; import org.onap.sdc.utils.DistributionStatusEnum; -public class DistributionStatusMessageImplTest { +class DistributionStatusMessageImplTest { private static final String ARTIFACT = "ARTIFACT"; private static final String DISTRIBUTION_ID = "DISTRIBUTION_ID"; @@ -35,7 +35,7 @@ public class DistributionStatusMessageImplTest { private static final String COMPONENT_NAME = "COMPONENT_NAME"; @Test - public void shouldProperlySetPropertiesFromIDistributionStatusMessage() { + void shouldProperlySetPropertiesFromIDistributionStatusMessage() { IDistributionStatusMessage copyFrom = new IDistributionStatusMessage() { @Override public String getArtifactURL() { @@ -72,7 +72,7 @@ public class DistributionStatusMessageImplTest { } @Test - public void shouldProperlySetPropertiesFromIComponentDoneStatusMessage() { + void shouldProperlySetPropertiesFromIComponentDoneStatusMessage() { IComponentDoneStatusMessage copyFrom = new IComponentDoneStatusMessage() { @Override public String getComponentName() { @@ -109,7 +109,7 @@ public class DistributionStatusMessageImplTest { } @Test - public void shouldProperlySetPropertiesFromIFinalDistrStatusMessage() { + void shouldProperlySetPropertiesFromIFinalDistrStatusMessage() { IFinalDistrStatusMessage copyFrom = new IFinalDistrStatusMessage() { @Override @@ -135,4 +135,4 @@ public class DistributionStatusMessageImplTest { assertEquals(result.getTimestamp(), copyFrom.getTimestamp()); } -}
\ No newline at end of file +} diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java index 815d749..37c4fe4 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/HeatParserTest.java @@ -7,9 +7,9 @@ * 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. @@ -20,120 +20,119 @@ package org.onap.sdc.impl; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import com.google.common.base.Charsets; +import com.google.common.io.Resources; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - -import org.junit.Test; -import org.onap.sdc.utils.heat.HeatParser; +import org.junit.jupiter.api.Test; import org.onap.sdc.utils.heat.HeatParameter; import org.onap.sdc.utils.heat.HeatParameterConstraint; +import org.onap.sdc.utils.heat.HeatParser; -import com.google.common.base.Charsets; -import com.google.common.io.Resources; - -public class HeatParserTest { - - @Test - public void testParametersParsing() throws IOException{ - String resourceName = "heatExample.yaml"; - URL url = Resources.getResource(resourceName); - String heatFileContents = Resources.toString(url, Charsets.UTF_8); - assertNotNull("Didn't find "+resourceName, heatFileContents); - - HeatParser heatParser = new HeatParser(); - //Flat parameter entry - Map<String, HeatParameter> parameters = heatParser.getHeatParameters(heatFileContents); - HeatParameter heatParameter1 = parameters.get("image_name_1"); - validateField("string", heatParameter1.getType(), "type"); - validateField("Image Name", heatParameter1.getLabel(), "label"); - validateField("SCOIMAGE Specify an image name for instance1", heatParameter1.getDescription(), "description"); - validateField("cirros-0.3.1-x86_64", heatParameter1.getDefault(), "default"); - validateField(null, heatParameter1.getConstraints(), "constraints"); - validateField("false", heatParameter1.getHidden(), "hidden"); - - - //Flat parameter entry with constraints - heatParameter1 = parameters.get("network_id"); - validateField("string", heatParameter1.getType(), "type"); - validateField("Network ID", heatParameter1.getLabel(), "label"); - validateField("SCONETWORK Network to be used for the compute instance", heatParameter1.getDescription(), "description"); - validateField(null, heatParameter1.getDefault(), "default"); - validateField("true", heatParameter1.getHidden(), "hidden"); - - //Constraints - List<HeatParameterConstraint> constraints = heatParameter1.getConstraints(); - assertEquals("Number of constraints", 6, constraints.size()); - - //Length - HeatParameterConstraint lengthConstraint = heatParameter1.getLengthConstraint(); - assertNotNull(lengthConstraint); - Map<String, String> expectedMap = new HashMap<>(); - expectedMap.put("min", "6"); - expectedMap.put("max", "8"); - validateField(expectedMap, lengthConstraint.getLength(), "length"); - validateField("Password length must be between 6 and 8 characters.", lengthConstraint.getDescription(), "length description"); - - //Range - HeatParameterConstraint rangeConstraint = heatParameter1.getRangeConstraint(); - assertNotNull(rangeConstraint); - validateField(expectedMap, rangeConstraint.getRange(), "range"); - validateField("Range description", rangeConstraint.getDescription(), "range description"); - - //Allowed values - HeatParameterConstraint allowedValues = heatParameter1.getAllowedValuesConstraint(); - assertNotNull(allowedValues); - List<String> expectedValues = new ArrayList<>(); - expectedValues.add("m1.small"); - expectedValues.add("m1.medium"); - expectedValues.add("m1.large"); - validateField(expectedValues, allowedValues.getAllowed_values(), "allowed_values"); - validateField("Allowed values description", allowedValues.getDescription(), "allowed_values description"); - - //Allowed pattern - List<HeatParameterConstraint> allowedPatternList = heatParameter1.getAllowedPatternConstraint(); - assertNotNull(allowedPatternList); - assertEquals("Allowed pattern list", 2, allowedPatternList.size()); - HeatParameterConstraint allowedPattern = allowedPatternList.get(0); - validateField("[a-zA-Z0-9]+", allowedPattern.getAllowed_pattern(), "allowed_pattern"); - validateField("Password must consist of characters and numbers only.", allowedPattern.getDescription(), "allowed_pattern description"); - allowedPattern = allowedPatternList.get(1); - validateField("[A-Z]+[a-zA-Z0-9]*", allowedPattern.getAllowed_pattern(), "allowed_pattern"); - validateField("Password must start with an uppercase character.", allowedPattern.getDescription(), "allowed_pattern description"); - - //Custom constraint - List<HeatParameterConstraint> customConstraintList = heatParameter1.getCustomConstraintConstraint(); - assertNotNull(customConstraintList); - assertEquals("Custom constraint list", 1, customConstraintList.size()); - HeatParameterConstraint customConstraint = customConstraintList.get(0); - validateField("nova.keypair", customConstraint.getCustom_constraint(), "custom_constraint"); - validateField("Custom description", customConstraint.getDescription(), "custom_constraint description"); - } - - @Test - public void testParametersParsingInvalidYaml() throws IOException{ - String invalidHeatFileContents = "just text"; - HeatParser heatParser = new HeatParser(); - //Flat parameter entry - Map<String, HeatParameter> parameters = heatParser.getHeatParameters(invalidHeatFileContents); - assertNull(parameters); - } - - @Test - public void testParametersParsingNoParamteresSection() throws IOException{ - String heatFileContentsNoParams = "heat_template_version: 2013-05-23\r\n\r\ndescription: Simple template to deploy a stack with two virtual machine instances"; - HeatParser heatParser = new HeatParser(); - //Flat parameter entry - Map<String, HeatParameter> parameters = heatParser.getHeatParameters(heatFileContentsNoParams); - assertNull(parameters); - } - - private void validateField(Object expected, Object actual, String type){ - assertEquals("Field of type "+type+":", expected, actual); - } +class HeatParserTest { + + @Test + void testParametersParsing() throws IOException { + String resourceName = "heatExample.yaml"; + URL url = Resources.getResource(resourceName); + String heatFileContents = Resources.toString(url, Charsets.UTF_8); + assertNotNull("Didn't find " + resourceName, heatFileContents); + + HeatParser heatParser = new HeatParser(); + //Flat parameter entry + Map<String, HeatParameter> parameters = heatParser.getHeatParameters(heatFileContents); + HeatParameter heatParameter1 = parameters.get("image_name_1"); + validateField("string", heatParameter1.getType(), "type"); + validateField("Image Name", heatParameter1.getLabel(), "label"); + validateField("SCOIMAGE Specify an image name for instance1", heatParameter1.getDescription(), "description"); + validateField("cirros-0.3.1-x86_64", heatParameter1.getDefault(), "default"); + validateField(null, heatParameter1.getConstraints(), "constraints"); + validateField("false", heatParameter1.getHidden(), "hidden"); + + //Flat parameter entry with constraints + heatParameter1 = parameters.get("network_id"); + validateField("string", heatParameter1.getType(), "type"); + validateField("Network ID", heatParameter1.getLabel(), "label"); + validateField("SCONETWORK Network to be used for the compute instance", heatParameter1.getDescription(), "description"); + validateField(null, heatParameter1.getDefault(), "default"); + validateField("true", heatParameter1.getHidden(), "hidden"); + + //Constraints + List<HeatParameterConstraint> constraints = heatParameter1.getConstraints(); + assertEquals(6, constraints.size(), "Number of constraints"); + + //Length + HeatParameterConstraint lengthConstraint = heatParameter1.getLengthConstraint(); + assertNotNull(lengthConstraint); + Map<String, String> expectedMap = new HashMap<>(); + expectedMap.put("min", "6"); + expectedMap.put("max", "8"); + validateField(expectedMap, lengthConstraint.getLength(), "length"); + validateField("Password length must be between 6 and 8 characters.", lengthConstraint.getDescription(), "length description"); + + //Range + HeatParameterConstraint rangeConstraint = heatParameter1.getRangeConstraint(); + assertNotNull(rangeConstraint); + validateField(expectedMap, rangeConstraint.getRange(), "range"); + validateField("Range description", rangeConstraint.getDescription(), "range description"); + + //Allowed values + HeatParameterConstraint allowedValues = heatParameter1.getAllowedValuesConstraint(); + assertNotNull(allowedValues); + List<String> expectedValues = new ArrayList<>(); + expectedValues.add("m1.small"); + expectedValues.add("m1.medium"); + expectedValues.add("m1.large"); + validateField(expectedValues, allowedValues.getAllowed_values(), "allowed_values"); + validateField("Allowed values description", allowedValues.getDescription(), "allowed_values description"); + + //Allowed pattern + List<HeatParameterConstraint> allowedPatternList = heatParameter1.getAllowedPatternConstraint(); + assertNotNull(allowedPatternList); + assertEquals(2, allowedPatternList.size(), "Allowed pattern list"); + HeatParameterConstraint allowedPattern = allowedPatternList.get(0); + validateField("[a-zA-Z0-9]+", allowedPattern.getAllowed_pattern(), "allowed_pattern"); + validateField("Password must consist of characters and numbers only.", allowedPattern.getDescription(), "allowed_pattern description"); + allowedPattern = allowedPatternList.get(1); + validateField("[A-Z]+[a-zA-Z0-9]*", allowedPattern.getAllowed_pattern(), "allowed_pattern"); + validateField("Password must start with an uppercase character.", allowedPattern.getDescription(), "allowed_pattern description"); + + //Custom constraint + List<HeatParameterConstraint> customConstraintList = heatParameter1.getCustomConstraintConstraint(); + assertNotNull(customConstraintList); + assertEquals(1, customConstraintList.size(), "Custom constraint list"); + HeatParameterConstraint customConstraint = customConstraintList.get(0); + validateField("nova.keypair", customConstraint.getCustom_constraint(), "custom_constraint"); + validateField("Custom description", customConstraint.getDescription(), "custom_constraint description"); + } + + @Test + void testParametersParsingInvalidYaml() throws IOException { + String invalidHeatFileContents = "just text"; + HeatParser heatParser = new HeatParser(); + //Flat parameter entry + Map<String, HeatParameter> parameters = heatParser.getHeatParameters(invalidHeatFileContents); + assertNull(parameters); + } + + @Test + void testParametersParsingNoParamteresSection() throws IOException { + String heatFileContentsNoParams = "heat_template_version: 2013-05-23\r\n\r\ndescription: Simple template to deploy a stack with two virtual machine instances"; + HeatParser heatParser = new HeatParser(); + //Flat parameter entry + Map<String, HeatParameter> parameters = heatParser.getHeatParameters(heatFileContentsNoParams); + assertNull(parameters); + } + + private void validateField(Object expected, Object actual, String type) { + assertEquals(expected, actual, "Field of type " + type + ":"); + } } 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 6b52801..1e3db81 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 @@ -8,9 +8,9 @@ * 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. @@ -21,333 +21,394 @@ package org.onap.sdc.impl; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +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.Arrays; +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.junit.Before; -import org.junit.Test; +import org.awaitility.Durations; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.onap.sdc.utils.TestConfiguration; import org.onap.sdc.api.consumer.INotificationCallback; import org.onap.sdc.api.notification.INotificationData; import org.onap.sdc.api.results.IDistributionClientResult; 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 com.att.nsa.cambria.client.CambriaConsumer; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -public class NotificationConsumerTest { - private CambriaConsumer cambriaConsumer = mock(CambriaConsumer.class); - private INotificationCallback clientCallback = spy(INotificationCallback.class); - private Queue<Iterable<String>> notificationsQueue = new LinkedList<>(); - private DistributionClientImpl distributionClient = Mockito.spy(DistributionClientImpl.class); - private List<String> artifactsTypes = Arrays.asList(ArtifactTypeEnum.HEAT.name()); - private List<Boolean> notificationStatusResults = new ArrayList<>(); - final static IDistributionClientResult DISTRIBUTION_SUCCESS_RESULT = buildSuccessResult(); - - private NotificationConsumer createNotificationConsumer() { - return new NotificationConsumer(cambriaConsumer, clientCallback, artifactsTypes, distributionClient); - } - - @Before - public void beforeTest() throws IOException { - Mockito.reset(clientCallback, distributionClient); - when(cambriaConsumer.fetch()).then(new Answer<Iterable<String>>() { - @Override - public Iterable<String> answer(InvocationOnMock invocation) throws Throwable { - if (!notificationsQueue.isEmpty()) { - return notificationsQueue.remove(); - } else { - return new ArrayList<>(); - } - } - }); - when(distributionClient.sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean())).then(new Answer<IDistributionClientResult>() { - @Override - public IDistributionClientResult answer(InvocationOnMock invocation) throws Throwable { - boolean isNotified = (boolean) invocation.getArguments()[3]; - notificationStatusResults.add(Boolean.valueOf(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 - public 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 - public void testNonRelevantNotificationSent() throws InterruptedException { - - simulateNotificationFromUEB(getAsdcServiceNotificationWithoutHeatArtifact()); - Mockito.verify(clientCallback, Mockito.times(0)).activateCallback(Mockito.any(INotificationData.class)); - - } - - @Test - public void testRelevantNotificationSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); - Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); - - } - - @Test - public void testNonExistingArtifactsNotificationSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcNotificationWithNonExistentArtifact()); - Mockito.verify(clientCallback, Mockito.times(1)).activateCallback(Mockito.any(INotificationData.class)); - - } - - @Test - public void testNotificationStatusSent() throws InterruptedException { - simulateNotificationFromUEB(getAsdcServiceNotificationWithHeatArtifact()); - - Mockito.verify(distributionClient, Mockito.times(3)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); - assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 1); - assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 2); - } - - @Test - public 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(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); - assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 3); - assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 0); - } - - @Test - public void testNotificationStatusWithServiceArtifatcs() throws InterruptedException { - simulateNotificationFromUEB(getNotificationWithServiceArtifatcs()); - Mockito.verify(distributionClient, Mockito.times(6)).sendNotificationStatus(Mockito.anyLong(), Mockito.anyString(), Mockito.any(ArtifactInfoImpl.class), Mockito.anyBoolean()); - assertTrue(countInstances(notificationStatusResults, Boolean.TRUE) == 2); - assertTrue(countInstances(notificationStatusResults, Boolean.FALSE) == 4); - - } - - @Test - public 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); - assertTrue(notificationBuiltInClient.getResources().size() == 1); - } - - @Test - public 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); - assertTrue(notificationBuiltInClient.getResources().size() == 2); - } - - private void simulateNotificationFromUEB(final String notificationFromUEB) throws InterruptedException { - ScheduledExecutorService executorPool = Executors.newScheduledThreadPool(DistributionClientConstants.POOL_SIZE); - executorPool.scheduleAtFixedRate(createNotificationConsumer(), 0, 100, TimeUnit.MILLISECONDS); - - Thread.sleep(200); - - List<String> nonHeatNotification = Arrays.asList(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; - } +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; + } } diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/StatusDataImplTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/impl/StatusDataImplTest.java deleted file mode 100644 index 82416fa..0000000 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/impl/StatusDataImplTest.java +++ /dev/null @@ -1,42 +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.impl; - -import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanToStringExcluding; -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -public class StatusDataImplTest { - - private static final String COMPONENT_NAME = "componentName"; - private static final String ERROR_REASON = "errorReason"; - - @Test - public void shouldHaveValidGettersAndSetters() { - assertThat(StatusDataImpl.class, hasValidGettersAndSettersExcluding(COMPONENT_NAME, ERROR_REASON)); - } - - @Test - public void shouldHaveValidToString() { - assertThat(StatusDataImpl.class, hasValidBeanToStringExcluding(COMPONENT_NAME, ERROR_REASON)); - } -}
\ No newline at end of file diff --git a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/GeneralUtilsTest.java b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/GeneralUtilsTest.java index 3ed80c3..b18b8a8 100644 --- a/sdc-distribution-client/src/test/java/org/onap/sdc/utils/GeneralUtilsTest.java +++ b/sdc-distribution-client/src/test/java/org/onap/sdc/utils/GeneralUtilsTest.java @@ -20,22 +20,22 @@ package org.onap.sdc.utils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.base.Charsets; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import java.util.Base64; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class GeneralUtilsTest { +class GeneralUtilsTest { private static final String TEXT_TO_CODE = "This is example text."; @Test - public void shouldCalculateMD5ForBytes() { + void shouldCalculateMD5ForBytes() { String hashed = GeneralUtils.calculateMD5(TEXT_TO_CODE.getBytes()); byte[] decoded = Base64.getDecoder().decode(hashed); HashCode expected = Hashing.md5().hashString(TEXT_TO_CODE, Charsets.UTF_8); @@ -43,7 +43,7 @@ public class GeneralUtilsTest { } @Test - public void shouldCalculateMD5ForString() { + void shouldCalculateMD5ForString() { String hashed = GeneralUtils.calculateMD5(TEXT_TO_CODE); byte[] decoded = Base64.getDecoder().decode(hashed); HashCode expected = Hashing.md5().hashString(TEXT_TO_CODE, Charsets.UTF_8); @@ -51,16 +51,16 @@ public class GeneralUtilsTest { } @Test - public void shouldValidateBase64EncodedString() { + void shouldValidateBase64EncodedString() { HashCode expected = Hashing.md5().hashString(TEXT_TO_CODE, Charsets.UTF_8); String base64String = Base64.getEncoder().encodeToString(expected.asBytes()); assertTrue(GeneralUtils.isBase64Encoded(base64String)); } @Test - public void shouldInvalidateBase64EncodedString() { + void shouldInvalidateBase64EncodedString() { String base64String = Base64.getEncoder().encodeToString(TEXT_TO_CODE.getBytes()); assertFalse(GeneralUtils.isBase64Encoded(base64String)); } -}
\ 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 0be7793..4d61542 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,40 +20,38 @@ package org.onap.sdc.utils; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaPublisher; -import fj.data.Either; -import org.junit.Test; -import org.onap.sdc.api.results.IDistributionClientResult; -import org.onap.sdc.impl.DistributionClientResultImpl; - -import java.io.IOException; -import java.util.Collections; -import java.util.List; - -import static org.junit.Assert.assertEquals; +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.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 org.junit.jupiter.api.Test; +import org.onap.sdc.api.results.IDistributionClientResult; +import org.onap.sdc.impl.DistributionClientResultImpl; -public class NotificationSenderTest { +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 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 NotificationSender validNotificationSender = new NotificationSender(emptyServers); @Test - public void whenPublisherIsValidAndNoExceptionsAreThrownShouldReturnSuccessStatus() throws IOException, InterruptedException { + void whenPublisherIsValidAndNoExceptionsAreThrownShouldReturnSuccessStatus() throws IOException, InterruptedException { //given when(publisher.send(anyString(), anyString())).thenReturn(0); when(publisher.close(anyLong(), any())).thenReturn(Collections.emptyList()); @@ -66,7 +64,7 @@ public class NotificationSenderTest { } @Test - public void whenPublisherCouldNotSendShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { + void whenPublisherCouldNotSendShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { //given when(publisher.send(anyString(), anyString())).thenReturn(0); when(publisher.close(anyLong(), any())).thenReturn(notEmptySendingFailedMessages); @@ -79,7 +77,7 @@ public class NotificationSenderTest { } @Test - public void whenSendingThrowsIOExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { + void whenSendingThrowsIOExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { //given when(publisher.send(anyString(), anyString())).thenThrow(new IOException()); when(publisher.close(anyLong(), any())).thenReturn(notEmptySendingFailedMessages); @@ -92,9 +90,11 @@ public class NotificationSenderTest { } @Test - public void whenSendingThrowsInterruptedExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { + void whenSendingThrowsInterruptedExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { //given - when(publisher.send(anyString(), anyString())).thenAnswer(invocationOnMock -> {throw new InterruptedException();}); + when(publisher.send(anyString(), anyString())).thenAnswer(invocationOnMock -> { + throw new InterruptedException(); + }); when(publisher.close(anyLong(), any())).thenReturn(notEmptySendingFailedMessages); //when @@ -105,7 +105,7 @@ public class NotificationSenderTest { } @Test - public void whenClosingThrowsIOExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { + void whenClosingThrowsIOExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { //given when(publisher.send(anyString(), anyString())).thenReturn(0); when(publisher.close(anyLong(), any())).thenThrow(new IOException()); @@ -118,10 +118,12 @@ public class NotificationSenderTest { } @Test - public void whenClosingThrowsInterruptedExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { + void whenClosingThrowsInterruptedExceptionShouldReturnGeneralErrorStatus() throws IOException, InterruptedException { //given when(publisher.send(anyString(), anyString())).thenReturn(0); - when(publisher.close(anyLong(), any())).thenAnswer(invocationOnMock -> {throw new InterruptedException();}); + when(publisher.close(anyLong(), any())).thenAnswer(invocationOnMock -> { + throw new InterruptedException(); + }); //when IDistributionClientResult result = validNotificationSender.send(publisher, status); @@ -129,4 +131,4 @@ public class NotificationSenderTest { //then assertEquals(generalErrorResponse.getDistributionActionResult(), result.getDistributionActionResult()); } -}
\ No newline at end of file +} |