diff options
author | Sonsino, Ofir (os0695) <os0695@intl.att.com> | 2018-07-10 14:20:54 +0300 |
---|---|---|
committer | Sonsino, Ofir (os0695) <os0695@intl.att.com> | 2018-07-10 14:20:54 +0300 |
commit | c72d565bb58226b20625b2bce5f0019046bee649 (patch) | |
tree | 8658e49595705b02e47ddc14afa20d6bb7123547 /vid-app-common/src/test/java | |
parent | ef8a6b47847012fd59ea20da21d8d3d7c4a301ed (diff) |
Merge 1806 code of vid-common
Change-Id: I75d52abed4a24dfe3827d79edc4a2938726aa87a
Issue-ID: VID-208
Signed-off-by: Sonsino, Ofir (os0695) <os0695@intl.att.com>
Diffstat (limited to 'vid-app-common/src/test/java')
53 files changed, 4671 insertions, 2483 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java index 8010447c..32e894d0 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java @@ -1,40 +1,453 @@ package org.onap.vid.aai; -import static org.junit.Assert.*; -import java.util.*; - -import org.json.simple.JSONObject; -import org.junit.Assert; -import org.junit.Test; -import org.onap.vid.aai.model.AaiGetPnfs.Pnf; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.mockito.Mockito; +import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; +import org.onap.vid.aai.model.AaiNodeQueryResponse; +import org.onap.vid.aai.model.ResourceType; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.model.Subscriber; import org.onap.vid.model.SubscriberList; +import org.onap.vid.model.probes.ExternalComponentStatus; +import org.onap.vid.model.probes.HttpRequestMetadata; +import org.onap.vid.model.probes.StatusMetadata; +import org.onap.vid.controllers.LocalWebConfig; +import org.onap.vid.testUtils.TestUtils; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.http.HttpMethod; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.web.WebAppConfiguration; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import sun.security.provider.certpath.SunCertPathBuilderException; +import sun.security.validator.ValidatorException; + +import javax.crypto.BadPaddingException; +import javax.net.ssl.SSLHandshakeException; +import javax.servlet.ServletContext; +import javax.ws.rs.ProcessingException; +import javax.ws.rs.client.Client; +import javax.ws.rs.core.Response; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.testng.Assert.*; +@ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) +@WebAppConfiguration public class AaiClientTest { - private AaiClient createTestSubject() { - return new AaiClient(); + private AaiClient aaiClientMock; + private ServletContext servletContext; + + @BeforeMethod + public void initMocks(){ + aaiClientMock = mock(AaiClient.class); + aaiClientMock.logger = mock(EELFLoggerDelegate.class); + servletContext = mock(ServletContext.class); + + when(servletContext.getRealPath(any(String.class))).thenReturn(""); + + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(null); + } + + @DataProvider + public static Object[][] logicalLinkData() { + return new Object[][] { + {"", "network/logical-links/logical-link/"}, + {"link", "network/logical-links/logical-link/link"} + }; + } + + @Test(dataProvider = "logicalLinkData") + public void getLogicalLink_Link_Is_Empty(String link, String expectedUrl) { + + when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod(); + aaiClientMock.getLogicalLink(link); + Mockito.verify(aaiClientMock).doAaiGet(argThat(equalToIgnoringCase(expectedUrl)),any(Boolean.class)); + } + + @DataProvider + public static Object[][] subscribersResults() { + return new Object[][] { + {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); add(new Subscriber()); }}), true}, + {new SubscriberList(new ArrayList<Subscriber>() {{ add(new Subscriber()); }}), true}, + {new SubscriberList(new ArrayList<Subscriber>()), false} + }; + } + + @Test(dataProvider = "subscribersResults") + public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable){ + ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI,isAvailable, new HttpRequestMetadata( + HttpMethod.GET, + 200, + "url", + "rawData", + isAvailable ? "OK" : "No subscriber received", + 0 + )); + Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn( + new AaiResponseWithRequestInfo<>( + HttpMethod.GET, "url", new AaiResponse<>(subscribers, null, 200), + "rawData")); + Mockito.when(aaiClientMock.probeAaiGetAllSubscribers()).thenCallRealMethod(); + ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); + assertThat(statusDataReflected(result),is(statusDataReflected(expectedStatus))); + assertThat(requestMetadataReflected(result.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata()))); + } + + //serialize fields except of fields we cannot know ahead of time + private static String requestMetadataReflected(StatusMetadata metadata) { + return new ReflectionToStringBuilder(metadata, ToStringStyle.SHORT_PREFIX_STYLE) + .setExcludeFieldNames("duration") + .toString(); + } + + private static String statusDataReflected(ExternalComponentStatus status) { + return new ReflectionToStringBuilder(status, ToStringStyle.SHORT_PREFIX_STYLE) + .setExcludeFieldNames("metadata") + .toString(); + } + + @DataProvider + public static Object[][] rawData() { + return new Object[][]{ + {"errorMessage", }, {""}, {null} + }; + } + + @Test(dataProvider = "rawData") + public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData){ + Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn( + new AaiResponseWithRequestInfo<>(HttpMethod.GET, "url", null, + rawData)); + ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable(); + assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class)); + assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), rawData); + } + + @DataProvider + public static Object[][] exceptions() { + return new Object[][] { + {"NullPointerException", "errorMessage", + new ExceptionWithRequestInfo(HttpMethod.GET, "url", + "errorMessage", null, new NullPointerException())}, + {"RuntimeException", null, + new ExceptionWithRequestInfo(HttpMethod.GET, "url", + null, null, new RuntimeException())}, + {"RuntimeException", null, + new RuntimeException()}, + }; + } + + @Test(dataProvider = "exceptions") + public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception){ + Mockito.when(aaiClientMock.getAllSubscribers(true)).thenThrow(exception); + ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable(); + if (exception instanceof ExceptionWithRequestInfo) { + assertThat(result.getMetadata(), instanceOf(HttpRequestMetadata.class)); + assertEquals(((HttpRequestMetadata) result.getMetadata()).getRawData(), expectedRawData); + } + assertThat(result.getMetadata().getDescription(), containsString(description)); + } + + private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() { + Mockito.when(aaiClientMock.probeAaiGetAllSubscribers()).thenCallRealMethod(); + ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); + assertFalse(result.isAvailable()); + return result; } @Test - public void testDoAaiGet() throws Exception { - AaiClient testSubject; - String certiPath = ""; - String uri = ""; - boolean xml = false; + public void getTenants_Arguments_Are_Null_Or_Empty() { + + when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod(); - // default test - testSubject = createTestSubject(); - testSubject.doAaiGet(certiPath, uri, xml); + AaiResponse response = aaiClientMock.getTenants("", ""); + + assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}"); + + + response = aaiClientMock.getTenants(null, null); + + assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}"); } @Test - public void testParseServiceSubscriptionObjectForTenants() throws Exception { - JSONObject jsonObject = null; - String result; + public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() { + + when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod(); + + Response generalEmptyResponse = mock(Response.class); + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse); + + AaiResponse response = aaiClientMock.getTenants("subscriberId", "serviceType"); + + assertEquals(response.getErrorMessage(), "{\"statusText\":\" A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'\"}"); - // default test - result = AaiClient.parseServiceSubscriptionObjectForTenants(jsonObject); } -}
\ No newline at end of file + @Test + public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() { + + when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod(); + + + Response generalEmptyResponse = mock(Response.class); + + when(generalEmptyResponse.readEntity(String.class)).thenReturn(tenantResponseRaw); + when(generalEmptyResponse.getStatus()).thenReturn(200); + when(generalEmptyResponse.getStatusInfo()).thenReturn(new Response.StatusType() { + @Override + public int getStatusCode() { + return 200; + } + + @Override + public Response.Status.Family getFamily() { + return Response.Status.Family.SUCCESSFUL; + } + + @Override + public String getReasonPhrase() { + return null; + } + }); + + + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse); + + AaiResponse<GetTenantsResponse[]> response = aaiClientMock.getTenants("subscriberId", "serviceType"); + + Assert.assertTrue(response.t.length> 0); + } + + final String tenantResponseRaw ="" + + "{" + + "\"service-type\": \"VIRTUAL USP\"," + + "\"resource-version\": \"1494001841964\"," + + "\"relationship-list\": {" + + "\"relationship\": [{" + + "\"related-to\": \"tenant\"," + + "\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," + + "\"relationship-data\": [{" + + "\"relationship-key\": \"cloud-region.cloud-owner\"," + + "\"relationship-value\": \"att-aic\"" + + "}," + + "{" + + "\"relationship-key\": \"cloud-region.cloud-region-id\"," + + "\"relationship-value\": \"AAIAIC25\"" + + "}," + + "{" + + "\"relationship-key\": \"tenant.tenant-id\"," + + "\"relationship-value\": \"092eb9e8e4b7412e8787dd091bc58e86\"" + + "}" + + "]," + + "\"related-to-property\": [{" + + "\"property-key\": \"tenant.tenant-name\"," + + "\"property-value\": \"USP-SIP-IC-24335-T-01\"" + + "}]" + + "}]" + + "}" + + "}"; + + @DataProvider + public static Object[][] resourceTypesProvider() { + return new Object[][] { + {"service-instance", ResourceType.SERVICE_INSTANCE}, + {"generic-vnf", ResourceType.GENERIC_VNF}, + {"vf-module", ResourceType.VF_MODULE} + }; + } + + @Test(dataProvider = "resourceTypesProvider") + public void aaiNodeQueryResponseDeserializationTest(String resourceType, ResourceType expectedResourceType) throws IOException { + String link = "/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/Nimbus/service-instances/service-instance/7131d483-b450-406f-8e30-0c650645fc67"; + String json = + "{\"result-data\": [{" + + "\"resource-type\": \""+resourceType+"\"," + + "\"resource-link\": \""+ link+ "\"" + + "}]}"; + + AaiNodeQueryResponse nodeQueryResponse = new ObjectMapper().readValue(json, AaiNodeQueryResponse.class); + assertThat(nodeQueryResponse.resultData.get(0).resourceLink, equalTo(link)); + assertThat(nodeQueryResponse.resultData.get(0).resourceType, is(expectedResourceType)); + } + + @Test + public void aaiNodeQueryEmptyResponseDeserializationTest() throws IOException{ + String json = "{}"; + AaiNodeQueryResponse nodeQueryResponse = new ObjectMapper().readValue(json, AaiNodeQueryResponse.class); + assertNull(nodeQueryResponse.resultData); + } + + @DataProvider + public static Object[][] nameAndResourceTypeProvider() { + return new Object[][] { + {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:SRIOV_SVC"}, + {"b1707vidnf", ResourceType.GENERIC_VNF, "search/nodes-query?search-node-type=generic-vnf&filter=vnf-name:EQUALS:b1707vidnf"}, + {"connectivity_test", ResourceType.VF_MODULE, "search/nodes-query?search-node-type=vf-module&filter=vf-module-name:EQUALS:connectivity_test"}, + {"MjVg1234", ResourceType.VOLUME_GROUP, "search/nodes-query?search-node-type=volume-group&filter=volume-group-name:EQUALS:MjVg1234"} + }; + } + + @Test(dataProvider = "nameAndResourceTypeProvider") + public void whenSearchNodeTypeByName_callRightAaiPath(String name, ResourceType type, String expectedUrl) { + when(aaiClientMock.searchNodeTypeByName(any(String.class), any(ResourceType.class))).thenCallRealMethod(); + aaiClientMock.searchNodeTypeByName(name, type); + Mockito.verify(aaiClientMock).doAaiGet(eq(expectedUrl), eq(false)); + } + + @DataProvider + public static Object[][] aaiClientInternalExceptions() { + return Stream.<Pair<Class<? extends Throwable>, UncheckedBiConsumer<HttpsAuthClient, Client>>>of( + + // Exception out of httpsAuthClientMock + Pair.of(CertificateException.class, (httpsAuthClientMock, javaxClientMock) -> { + final CertificateException e0 = new CertificateException("No X509TrustManager implementation available"); + SSLHandshakeException e = new SSLHandshakeException(e0.toString()); + e.initCause(e0); + + when(httpsAuthClientMock.getClient(any())).thenThrow(e); + }), + + Pair.of(StringIndexOutOfBoundsException.class, mockExceptionOnClientProvider(new StringIndexOutOfBoundsException(4))), + + Pair.of(NullPointerException.class, mockExceptionOnClientProvider(new NullPointerException("null"))), + + Pair.of(FileNotFoundException.class, mockExceptionOnClientProvider(new FileNotFoundException("vid/WEB-INF/cert/aai-client-cert.p12"))), + + Pair.of(BadPaddingException.class, mockExceptionOnClientProvider( + new IOException("keystore password was incorrect", new BadPaddingException("Given final block not properly padded"))) + ), + Pair.of(GenericUncheckedException.class, mockExceptionOnClientProvider(new GenericUncheckedException("basa"))), + + Pair.of(NullPointerException.class, (httpsAuthClientMock, javaxClientMock) -> + when(httpsAuthClientMock.getClient(any())).thenReturn(null)), + + + // Exception out of javax's Client + Pair.of(SSLHandshakeException.class, (httpsAuthClientMock, javaxClientMock) -> { + when(javaxClientMock.target(anyString())).thenThrow( + new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired")) + ); + }), + + Pair.of(SunCertPathBuilderException.class, (httpsAuthClientMock, javaxClientMock) -> { + SunCertPathBuilderException e0 = new SunCertPathBuilderException("unable to find valid certification path to requested target"); + when(javaxClientMock.target(anyString())).thenThrow( + new ProcessingException(new ValidatorException("PKIX path building failed: " + e0.toString(), e0)) + ); + }), + + Pair.of(GenericUncheckedException.class, (httpsAuthClientMock, javaxClientMock) -> + when(javaxClientMock.target(anyString())).thenThrow(new GenericUncheckedException("basa"))) + + ).flatMap(l -> Stream.of( + // double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work + ImmutableList.of(l.getLeft(), l.getRight(), true).toArray(), + ImmutableList.of(l.getLeft(), l.getRight(), false).toArray() + )).collect(Collectors.toList()).toArray(new Object[][]{}); + } + + private static UncheckedBiConsumer<HttpsAuthClient, Client> mockExceptionOnClientProvider(Exception e) { + return (httpsAuthClientMock, javaxClientMock) -> + when(httpsAuthClientMock.getClient(any())).thenThrow(e); + } + + @Test(dataProvider = "aaiClientInternalExceptions") + public void propagateExceptions_internalsThrowException_ExceptionRethrown(Class<? extends Throwable> expectedType, BiConsumer<HttpsAuthClient, Client> setupMocks, boolean propagateExceptions) throws Exception { + /* + Call chain is like: + this test -> AaiClient -> AAIRestInterface -> HttpsAuthClient -> javax's Client + + In this test, *AaiClient* and *AAIRestInterface* are under test (actual + implementation is used), while HttpsAuthClient and the javax's Client are + mocked to return pseudo-responses or - better- throw exceptions. + */ + + // prepare mocks + HttpsAuthClient httpsAuthClientMock = mock(HttpsAuthClient.class); + TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); + Client javaxClientMock = mocks.getFakeClient(); + Response responseMock = mocks.getFakeResponse(); + + // prepare real AAIRestInterface and AaiClient, and wire mocks + AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock); + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null); + when(httpsAuthClientMock.getClient(any())).thenReturn(javaxClientMock); + + // define atomic method under test, including reset of "aaiRestInterface.client" + final Function<Boolean, Response> doAaiGet = (propagateExceptions1) -> { + try { + FieldUtils.writeField(aaiRestInterface, "client", null, true); + return aaiClient.doAaiGet("uri", false, propagateExceptions1).getResponse(); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + }; + + // verify setup again + assertThat("mocks setup should make doAaiGet return our responseMock", doAaiGet.apply(true), is(sameInstance(responseMock))); + + + /// TEST: + setupMocks.accept(httpsAuthClientMock, javaxClientMock); + + try { + final Response response = doAaiGet.apply(propagateExceptions); + } catch (Exception e) { + if (propagateExceptions) { + assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType)); + return; // ok, done + } else { + // Verify that "don't propagate" really still work + Assert.fail("calling doAaiGet when propagateExceptions is false must result with no exception", e); + } + } + + // If no exception caught + // We're asserting that the legacy behaviour is still in place. Hopefully + // one day we will remove the non-propagateExceptions case + assertFalse(propagateExceptions, "calling doAaiGet when propagateExceptions is 'true' must result with an exception (in this test)"); + } + + @FunctionalInterface + public interface UncheckedBiConsumer<T, U> extends BiConsumer<T, U> { + @Override + default void accept(T t, U u) { + try { + acceptThrows(t, u); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + void acceptThrows(T t, U u) throws Exception; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/AAIRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/AAIRestInterfaceTest.java index 35ebb66e..3aa693c1 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/util/AAIRestInterfaceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/AAIRestInterfaceTest.java @@ -4,6 +4,9 @@ import org.junit.Test; public class AAIRestInterfaceTest { + /* + TO BE IMPLEMENTED + private AAIRestInterface createTestSubject() { return new AAIRestInterface(""); } @@ -72,5 +75,5 @@ public class AAIRestInterfaceTest { // default test testSubject = createTestSubject(); testSubject.RestPost(fromAppId, transId, path, payload, xml); - } + }*/ }
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java index 88d53c03..a26c431e 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/HttpsAuthClientTest.java @@ -4,6 +4,9 @@ import org.junit.Test; public class HttpsAuthClientTest { + /* + TO BE IMPLEMENTED + private HttpsAuthClient createTestSubject() { return new HttpsAuthClient(); } @@ -15,4 +18,5 @@ public class HttpsAuthClientTest { // default test HttpsAuthClient.getClient(certFilePath); } + */ }
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/BaseClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/BaseClientTest.java deleted file mode 100644 index 40a05fd9..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/BaseClientTest.java +++ /dev/null @@ -1,322 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID ASDC Client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.vid.asdc; - -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.UUID; - -import javax.ws.rs.NotFoundException; - -import org.hamcrest.core.IsEqual; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ErrorCollector; -import org.onap.vid.asdc.beans.Artifact; -import org.onap.vid.asdc.beans.Resource; -import org.onap.vid.asdc.beans.Service; -import org.onap.vid.asdc.beans.Service.DistributionStatus; -import org.onap.vid.asdc.beans.tosca.Group; -import org.onap.vid.asdc.beans.tosca.Input; -import org.onap.vid.asdc.beans.tosca.NodeTemplate; -import org.onap.vid.asdc.beans.tosca.ToscaCsar; -import org.onap.vid.asdc.beans.tosca.ToscaModel; - -/** - * The Class BaseClientTest. - */ -public class BaseClientTest { - - /** The collector. */ - @Rule - public ErrorCollector collector = new ErrorCollector(); - - /** - * Run resource tests. - * - * @param client the client - * @throws AsdcCatalogException the asdc catalog exception - */ - protected void runResourceTests(AsdcClient client) throws AsdcCatalogException { - final Collection<Resource> resources = client.getResources(); - - collector.checkThat("getResources() returned nothing", resources.isEmpty(), IsEqual.equalTo(false)); - - final Resource resource = resources.iterator().next(); - - testResource(resource); - - final Resource thisResource = client.getResource(UUID.fromString(resource.getUuid())); - - collector.checkThat(thisResource, IsEqual.equalTo(resource)); - - for (Resource aResource : resources) { - if (aResource.getArtifacts() != null && !aResource.getArtifacts().isEmpty()) { - - final Artifact artifact = aResource.getArtifacts().iterator().next(); - - testArtifact(artifact); - - final UUID resourceUuid = UUID.fromString(aResource.getUuid()); - final UUID artifactUuid = UUID.fromString(artifact.getArtifactUUID()); - final Artifact thisArtifact = client.getResourceArtifact(resourceUuid, artifactUuid); - - collector.checkThat(artifact, IsEqual.equalTo(thisArtifact)); - } - } - - try { - final Collection<Resource> badResources = client.getResources(Collections.singletonMap("category", new String[] {"Bad Resources"})); - - for (Resource badResource : badResources) { - collector.checkThat(badResource.getCategory(), IsEqual.equalTo("Bad Resources")); - } - } catch (NotFoundException e) { - //No resources of this category were found - } - - try { - final Collection<Resource> reallyBadResources = client.getResources(Collections.singletonMap("subCategory", new String[] {"Really Bad Resources"})); - - for (Resource reallyBadResource : reallyBadResources) { - collector.checkThat(reallyBadResource.getSubCategory(), IsEqual.equalTo("Really Bad Resources")); - } - } catch (NotFoundException e) { - //No resources of this subcategory were found - } - - /*final ToscaCsar toscaCsar = client.getResourceToscaModel(UUID.fromString(resource.getUuid())); - - testToscaCsar(toscaCsar);*/ - } - - /** - * Run service tests. - * - * @param client the client - * @throws AsdcCatalogException the asdc catalog exception - */ - protected void runServiceTests(AsdcClient client) throws AsdcCatalogException { - final Collection<Service> services = client.getServices(); - - collector.checkThat("getServices() returned nothing", services.isEmpty(), IsEqual.equalTo(false)); - - final Service service = services.iterator().next(); - - testService(service); - - final Service thisService = client.getService(UUID.fromString(service.getUuid())); - - collector.checkThat(thisService, IsEqual.equalTo(service)); - - for (Service aService : services) { - if (aService.getArtifacts() != null && ! aService.getArtifacts().isEmpty()) { - final Artifact artifact = aService.getArtifacts().iterator().next(); - - testArtifact(artifact); - - final UUID serviceUuid = UUID.fromString(aService.getUuid()); - final UUID artifactUuid = UUID.fromString(artifact.getArtifactUUID()); - final Artifact thisArtifact = client.getServiceArtifact(serviceUuid, artifactUuid); - - collector.checkThat(artifact, IsEqual.equalTo(thisArtifact)); - break; - } - } - - try { - final Collection<Service> distributedServices = client.getServices(Collections.singletonMap("distributionStatus", new String[] {"DISTRIBUTED"})); - - for (Service distributedService : distributedServices) { - collector.checkThat(distributedService.getDistributionStatus(), IsEqual.equalTo(DistributionStatus.DISTRIBUTED)); - } - } catch (NotFoundException e) { - //No services of this distributionStatus were found - } - - try { - final Collection<Service> badServices = client.getServices(Collections.singletonMap("category", new String[] {"Bad Services"})); - - for (Service badService : badServices) { - collector.checkThat(badService.getCategory(), IsEqual.equalTo("Bad Services")); - } - } catch (NotFoundException e) { - //No services of this category were found - } - - /*final ToscaCsar toscaCsar = client.getServiceToscaModel(UUID.fromString(service.getUuid())); - - testToscaCsar(toscaCsar);*/ - } - - /** - * Test service. - * - * @param service the service - */ - private void testService(Service service) { - service.getArtifacts(); - service.getCategory(); - service.getDistributionStatus(); - service.getInvariantUUID(); - service.getLastUpdaterUserId(); - service.getLastUpdaterFullName(); - service.getLifecycleState(); - service.getName(); - service.getResources(); - service.getToscaModelURL(); - service.getUuid(); - service.getVersion(); - } - - /** - * Test resource. - * - * @param resource the resource - */ - private void testResource(Resource resource) { - resource.getArtifacts(); - resource.getCategory(); - resource.getInvariantUUID(); - resource.getLastUpdaterUserId(); - resource.getLastUpdaterFullName(); - resource.getLifecycleState(); - resource.getName(); - resource.getResources(); - resource.getResourceType(); - resource.getSubCategory(); - resource.getToscaModel(); - resource.getToscaModelURL(); - resource.getToscaResourceName(); - resource.getUuid(); - resource.getVersion(); - } - - /** - * Test artifact. - * - * @param artifact the artifact - */ - private void testArtifact(Artifact artifact) { - artifact.getArtifactChecksum(); - artifact.getArtifactDescription(); - artifact.getArtifactName(); - artifact.getArtifactTimeout(); - artifact.getArtifactType(); - artifact.getArtifactURL(); - artifact.getArtifactUUID(); - artifact.getArtifactVersion(); - artifact.getGeneratedFromUUID(); - } - - /** - * Test tosca csar. - * - * @param toscaCsar the tosca csar - */ - private void testToscaCsar(ToscaCsar toscaCsar) { - testToscaModel(toscaCsar.getParent()); - - for (ToscaModel childModel : toscaCsar.getChildren()) { - testToscaModel(childModel); - } - } - - /** - * Test tosca model. - * - * @param toscaModel the tosca model - */ - private void testToscaModel(ToscaModel toscaModel) { - - toscaModel.getDescription(); - toscaModel.getMetadata().getCategory(); - toscaModel.getMetadata().getDescription(); - toscaModel.getMetadata().getInvariantUUID(); - toscaModel.getMetadata().getName(); - toscaModel.getMetadata().getType(); - toscaModel.getMetadata().gettemplate_name(); - toscaModel.getMetadata().getUUID(); - toscaModel.getMetadata().getVersion(); - //toscaModel.getMetadata().isServiceEcompNaming(); - toscaModel.getMetadata().isServiceHoming(); - - if (!toscaModel.gettopology_template().getInputs().isEmpty()) { - final Input input = toscaModel.gettopology_template().getInputs().values().iterator().next(); - input.getDefault(); - input.getDescription(); - input.getType(); - input.toString(); - } - - if (!toscaModel.gettopology_template().getnode_templates().isEmpty()) { - final NodeTemplate nodeTemplate = toscaModel.gettopology_template().getnode_templates().values().iterator().next(); - nodeTemplate.getMetadata(); - nodeTemplate.getProperties(); - nodeTemplate.getRequirements(); - nodeTemplate.getType(); - } - - if (!toscaModel.gettopology_template().getGroups().isEmpty()) { - final Group group = toscaModel.gettopology_template().getGroups().values().iterator().next(); - group.getMembers(); - group.getMetadata(); - group.getType(); - } - - if (!toscaModel.getImports().isEmpty()) { - for (Map<String, Map<String, String>> imports : toscaModel.getImports()) { - imports.values().iterator().next().get("file"); - } - } - - toscaModel.gettopology_template().getsubstitution_mappings().getnode_type(); - - if (!toscaModel.gettopology_template().getsubstitution_mappings().getCapabilities().isEmpty()) { - toscaModel.gettopology_template().getsubstitution_mappings().getCapabilities(); - } - - toscaModel.gettosca_definitions_version(); - } - - /** - * Test try catch asdc catalog exception. - */ - @Test - public void testTryCatchAsdcCatalogException() { - try { - throw new AsdcCatalogException("testing"); - } catch (AsdcCatalogException e) { - Assert.assertEquals("testing", e.getMessage()); - } - - final Exception cause = new Exception(); - - try { - throw new AsdcCatalogException("testing", cause); - } catch (AsdcCatalogException e) { - Assert.assertEquals("testing", e.getMessage()); - Assert.assertEquals(cause, e.getCause()); - } - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/InMemoryClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/InMemoryClientTest.java deleted file mode 100644 index 5687e628..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/InMemoryClientTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID ASDC Client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.vid.asdc; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URISyntaxException; - -import org.codehaus.jackson.map.ObjectMapper; -import org.json.JSONObject; -import org.json.JSONTokener; -import org.junit.Before; -import org.junit.Test; -import org.onap.vid.asdc.memory.InMemoryAsdcClient; - -/** - * The Class InMemoryClientTest. - */ -public class InMemoryClientTest extends BaseClientTest { - - /** The catalog. */ - private JSONObject catalog; - - /** - * Sets the up. - * - * @throws URISyntaxException the URI syntax exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Before - public void setUp() throws URISyntaxException, IOException { - final InputStream asdcCatalogFile = getClass().getClassLoader().getResourceAsStream("catalog.json"); - - final JSONTokener tokener = new JSONTokener(asdcCatalogFile); - - catalog = new JSONObject(tokener); - } - - /** - * Test resources. - * - * @throws AsdcCatalogException the asdc catalog exception - */ - @Test - public void testResources() throws AsdcCatalogException { - - runResourceTests(new InMemoryAsdcClient.Builder().catalog(catalog).mapper(new ObjectMapper()).build()); - } - - /** - * Test services. - * - * @throws AsdcCatalogException the asdc catalog exception - * @throws URISyntaxException the URI syntax exception - */ - @Test - public void testServices() throws AsdcCatalogException, URISyntaxException { - - runServiceTests(new InMemoryAsdcClient.Builder().catalog(catalog).build()); - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/RestfulClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/RestfulClientTest.java deleted file mode 100644 index ae056342..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/RestfulClientTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID ASDC Client - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. 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.vid.asdc; - -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Properties; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.vid.asdc.rest.RestfulAsdcClient; - -/** - * The Class RestfulClientTest. - */ -@Ignore -public class RestfulClientTest extends BaseClientTest { - - /** The rest client. */ - private Client restClient; - - /** The uri. */ - private URI uri; - - /** The properties. */ - private Properties properties; - - /** The auth. */ - private String auth; - - /** - * Sets the up. - * - * @throws URISyntaxException the URI syntax exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Before - public void setUp() throws URISyntaxException, IOException { - final InputStream propertiesFile = getClass().getClassLoader().getResourceAsStream("asdc.properties"); - - properties = new Properties(); - properties.load(propertiesFile); - - final String protocol = properties.getProperty("protocol", "http"); - - restClient = ClientBuilder.newBuilder() - .hostnameVerifier(new HostnameVerifier() { - - @Override - public boolean verify(String arg0, SSLSession arg1) { - return true; - } - }) - .build(); - uri = new URI(protocol + "://" + properties.getProperty("host", "localhost") + ":" + properties.getProperty("port", "80") + "/"); - auth = properties.getProperty("auth"); - } - - /** - * Test resources. - * - * @throws AsdcCatalogException the asdc catalog exception - */ - @Test - public void testResources() throws AsdcCatalogException { - - runResourceTests(new RestfulAsdcClient.Builder(restClient, uri).auth(auth).build()); - } - - /** - * Test services. - * - * @throws AsdcCatalogException the asdc catalog exception - * @throws URISyntaxException the URI syntax exception - */ - @Test - public void testServices() throws AsdcCatalogException, URISyntaxException { - - runServiceTests(new RestfulAsdcClient.Builder(restClient, uri).auth(auth).build()); - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/ResourceTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/ResourceTest.java deleted file mode 100644 index af42409c..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/ResourceTest.java +++ /dev/null @@ -1,391 +0,0 @@ -package org.onap.vid.asdc.beans; - -import java.util.Collection; - -import org.junit.Test; -import org.onap.vid.asdc.beans.Resource.LifecycleState; -import org.onap.vid.asdc.beans.Resource.Type; - - -public class ResourceTest { - - private Resource createTestSubject() { - return new Resource(); - } - - - @Test - public void testGetUuid() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getUuid(); - } - - - @Test - public void testGetInvariantUUID() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInvariantUUID(); - } - - - @Test - public void testGetName() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getName(); - } - - - @Test - public void testGetDescription() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDescription(); - } - - - @Test - public void testGetVersion() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getVersion(); - } - - - @Test - public void testGetToscaModelURL() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getToscaModelURL(); - } - - - @Test - public void testGetCategory() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCategory(); - } - - - @Test - public void testGetSubCategory() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getSubCategory(); - } - - - @Test - public void testGetResourceType() throws Exception { - Resource testSubject; - Type result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getResourceType(); - } - - - @Test - public void testGetLifecycleState() throws Exception { - Resource testSubject; - LifecycleState result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLifecycleState(); - } - - - @Test - public void testGetLastUpdaterUserId() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLastUpdaterUserId(); - } - - - @Test - public void testGetLastUpdaterFullName() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLastUpdaterFullName(); - } - - - @Test - public void testGetToscaModel() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getToscaModel(); - } - - - @Test - public void testGetToscaResourceName() throws Exception { - Resource testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getToscaResourceName(); - } - - - @Test - public void testGetArtifacts() throws Exception { - Resource testSubject; - Collection<Artifact> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getArtifacts(); - } - - - @Test - public void testGetResources() throws Exception { - Resource testSubject; - Collection<SubResource> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getResources(); - } - - - @Test - public void testSetUuid() throws Exception { - Resource testSubject; - String uuid = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setUuid(uuid); - } - - - @Test - public void testSetInvariantUUID() throws Exception { - Resource testSubject; - String invariantUUID = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setInvariantUUID(invariantUUID); - } - - - @Test - public void testSetName() throws Exception { - Resource testSubject; - String name = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setName(name); - } - - - @Test - public void testSetDescription() throws Exception { - Resource testSubject; - String description = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setDescription(description); - } - - - @Test - public void testSetVersion() throws Exception { - Resource testSubject; - String version = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setVersion(version); - } - - - @Test - public void testSetToscaModelURL() throws Exception { - Resource testSubject; - String toscaModelURL = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setToscaModelURL(toscaModelURL); - } - - - @Test - public void testSetCategory() throws Exception { - Resource testSubject; - String category = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setCategory(category); - } - - - @Test - public void testSetSubCategory() throws Exception { - Resource testSubject; - String subCategory = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setSubCategory(subCategory); - } - - - @Test - public void testSetResourceType() throws Exception { - Resource testSubject; - Type resourceType = null; - - // default test - testSubject = createTestSubject(); - testSubject.setResourceType(resourceType); - } - - - @Test - public void testSetLifecycleState() throws Exception { - Resource testSubject; - LifecycleState lifecycleState = null; - - // default test - testSubject = createTestSubject(); - testSubject.setLifecycleState(lifecycleState); - } - - - @Test - public void testSetLastUpdaterUserId() throws Exception { - Resource testSubject; - String lastUpdaterUserId = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setLastUpdaterUserId(lastUpdaterUserId); - } - - - @Test - public void testSetLastUpdaterFullName() throws Exception { - Resource testSubject; - String lastUpdaterFullName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setLastUpdaterFullName(lastUpdaterFullName); - } - - - @Test - public void testSetToscaModel() throws Exception { - Resource testSubject; - String toscaModel = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setToscaModel(toscaModel); - } - - - @Test - public void testSetToscaResourceName() throws Exception { - Resource testSubject; - String toscaResourceName = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setToscaResourceName(toscaResourceName); - } - - - @Test - public void testSetArtifacts() throws Exception { - Resource testSubject; - Collection<Artifact> artifacts = null; - - // default test - testSubject = createTestSubject(); - testSubject.setArtifacts(artifacts); - } - - - @Test - public void testSetResources() throws Exception { - Resource testSubject; - Collection<SubResource> resources = null; - - // default test - testSubject = createTestSubject(); - testSubject.setResources(resources); - } - - - @Test - public void testHashCode() throws Exception { - Resource testSubject; - int result; - - // default test - testSubject = createTestSubject(); - testSubject.setUuid("cb49608f-5a24-4789-b0f7-2595473cb997"); - result = testSubject.hashCode(); - } - - - @Test - public void testEquals() throws Exception { - Resource testSubject; - Object o = null; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.equals(o); - } -}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/CapabilityTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/CapabilityTest.java deleted file mode 100644 index 7609e36d..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/CapabilityTest.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.onap.vid.asdc.beans.tosca; - -import java.util.Collection; -import java.util.Map; - -import org.junit.Test; - - -public class CapabilityTest { - - private Capability createTestSubject() { - return new Capability(); - } - - - @Test - public void testGetType() throws Exception { - Capability testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getType(); - } - - - @Test - public void testGetDescription() throws Exception { - Capability testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getDescription(); - } - - - @Test - public void testGetOccurrences() throws Exception { - Capability testSubject; - Collection<String> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getOccurrences(); - } - - - @Test - public void testGetProperties() throws Exception { - Capability testSubject; - Map<String, Property> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getProperties(); - } - - - @Test - public void testGetValid_source_types() throws Exception { - Capability testSubject; - Collection<String> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValid_source_types(); - } - - - @Test - public void testSetType() throws Exception { - Capability testSubject; - String type = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setType(type); - } - - - @Test - public void testSetDescription() throws Exception { - Capability testSubject; - String description = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setDescription(description); - } - - - @Test - public void testSetOccurrences() throws Exception { - Capability testSubject; - Collection<String> occurrences = null; - - // default test - testSubject = createTestSubject(); - testSubject.setOccurrences(occurrences); - } - - - @Test - public void testSetProperties() throws Exception { - Capability testSubject; - Map<String, Property> properties = null; - - // default test - testSubject = createTestSubject(); - testSubject.setProperties(properties); - } - - - @Test - public void testSetValid_source_types() throws Exception { - Capability testSubject; - Collection<String> valid_source_types = null; - - // default test - testSubject = createTestSubject(); - testSubject.setValid_source_types(valid_source_types); - } -}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/ConstraintTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/ConstraintTest.java deleted file mode 100644 index ebba7d17..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/ConstraintTest.java +++ /dev/null @@ -1,221 +0,0 @@ -package org.onap.vid.asdc.beans.tosca; - -import java.util.List; - -import org.junit.Test; - -public class ConstraintTest { - - private Constraint createTestSubject() { - return new Constraint(); - } - - - @Test - public void testGetvalid_values() throws Exception { - Constraint testSubject; - List<Object> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getvalid_values(); - } - - - @Test - public void testGetEqual() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getEqual(); - } - - - @Test - public void testGetGreater_than() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGreater_than(); - } - - - @Test - public void testGetGreater_or_equal() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getGreater_or_equal(); - } - - - @Test - public void testGetLess_than() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLess_than(); - } - - - @Test - public void testGetLess_or_equal() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLess_or_equal(); - } - - - @Test - public void testGetIn_range() throws Exception { - Constraint testSubject; - List<Object> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getIn_range(); - } - - - @Test - public void testGetLength() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLength(); - } - - - @Test - public void testGetMin_length() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMin_length(); - } - - - @Test - public void testGetMax_length() throws Exception { - Constraint testSubject; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMax_length(); - } - - - @Test - public void testSetvalid_values() throws Exception { - Constraint testSubject; - List<Object> vlist = null; - - // default test - testSubject = createTestSubject(); - testSubject.setvalid_values(vlist); - } - - - @Test - public void testSetEqual() throws Exception { - Constraint testSubject; - Object e = null; - - // default test - testSubject = createTestSubject(); - testSubject.setEqual(e); - } - - - @Test - public void testSetGreater_than() throws Exception { - Constraint testSubject; - Object e = null; - - // default test - testSubject = createTestSubject(); - testSubject.setGreater_than(e); - } - - - @Test - public void testSetLess_than() throws Exception { - Constraint testSubject; - Object e = null; - - // default test - testSubject = createTestSubject(); - testSubject.setLess_than(e); - } - - - @Test - public void testSetIn_range() throws Exception { - Constraint testSubject; - List<Object> e = null; - - // default test - testSubject = createTestSubject(); - testSubject.setIn_range(e); - } - - - @Test - public void testSetLength() throws Exception { - Constraint testSubject; - Object e = null; - - // default test - testSubject = createTestSubject(); - testSubject.setLength(e); - } - - - @Test - public void testSetMin_length() throws Exception { - Constraint testSubject; - Object e = null; - - // default test - testSubject = createTestSubject(); - testSubject.setMin_length(e); - } - - - @Test - public void testSetMax_length() throws Exception { - Constraint testSubject; - Object e = null; - - // default test - testSubject = createTestSubject(); - testSubject.setMax_length(e); - } - - - @Test - public void testToString() throws Exception { - Constraint testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.toString(); - } -}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java index e638b518..cb68eac9 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/PropertyTest.java @@ -38,15 +38,6 @@ public class PropertyTest { result = testSubject.getEntry_schema(); } - @Test - public void testGet_default() throws Exception { - Property testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.get_default(); - } @Test public void testSetType() throws Exception { @@ -78,15 +69,6 @@ public class PropertyTest { testSubject.setEntry_schema(entry_schema); } - @Test - public void testSet_default() throws Exception { - Property testSubject; - String _default = ""; - - // default test - testSubject = createTestSubject(); - testSubject.set_default(_default); - } @Test public void testGetDefault() throws Exception { diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/RequirementTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/RequirementTest.java deleted file mode 100644 index ae5ff529..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/beans/tosca/RequirementTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.onap.vid.asdc.beans.tosca; - -import java.util.Collection; - -import org.junit.Test; - -public class RequirementTest { - - private Requirement createTestSubject() { - return new Requirement(); - } - - @Test - public void testGetOccurrences() throws Exception { - Requirement testSubject; - Collection<String> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getOccurrences(); - } - - @Test - public void testGetCapability() throws Exception { - Requirement testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCapability(); - } - - @Test - public void testGetNode() throws Exception { - Requirement testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getNode(); - } - - @Test - public void testGetRelationship() throws Exception { - Requirement testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRelationship(); - } - - @Test - public void testSetOccurrences() throws Exception { - Requirement testSubject; - Collection<String> occurrences = null; - - // default test - testSubject = createTestSubject(); - testSubject.setOccurrences(occurrences); - } - - @Test - public void testSetCapability() throws Exception { - Requirement testSubject; - String capability = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setCapability(capability); - } - - @Test - public void testSetNode() throws Exception { - Requirement testSubject; - String node = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setNode(node); - } - - @Test - public void testSetRelationship() throws Exception { - Requirement testSubject; - String relationship = ""; - - // default test - testSubject = createTestSubject(); - testSubject.setRelationship(relationship); - } -}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java index 9f572feb..1282a6f7 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java @@ -1,56 +1,288 @@ package org.onap.vid.asdc.parser; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; +import net.javacrumbs.jsonunit.JsonAssert; +import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; -import org.junit.Assert; -import org.onap.vid.controllers.WebConfig; -import org.onap.vid.model.VfModule; -import org.onap.vid.model.VolumeGroup; -import org.onap.vid.properties.AsdcClientConfiguration; -import org.onap.portalsdk.core.util.SystemProperties; +import org.json.JSONObject; +import org.json.JSONTokener; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.toscaparser.api.Group; import org.onap.sdc.toscaparser.api.NodeTemplate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.web.context.WebApplicationContext; -import org.testng.annotations.BeforeMethod; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.AsdcClient; +import org.onap.vid.asdc.local.LocalAsdcClient; +import org.onap.vid.model.*; +import org.onap.vid.controllers.ToscaParserMockHelper; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.Map; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.*; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.vid.testUtils.TestUtils.assertJsonStringEqualsIgnoreNulls; @Test -@ContextConfiguration(classes = { WebConfig.class, AsdcClientConfiguration.class, SystemProperties.class }) -@WebAppConfiguration -public class ToscaParserImpl2Test extends AbstractTestNGSpringContextTests { +public class ToscaParserImpl2Test { private final String myUUID = "myUUID"; private static final Logger log = Logger.getLogger(ToscaParserImpl2Test.class); - @Autowired - private ToscaParserImpl2 toscaParserImpl2; + private ToscaParserImpl2 toscaParserImpl2 = new ToscaParserImpl2(); + + private AsdcClient asdcClient; + private ObjectMapper om = new ObjectMapper(); + + @BeforeClass + void init() throws IOException { + + final InputStream asdcServicesFile = this.getClass().getClassLoader().getResourceAsStream("sdcservices.json"); + + final JSONTokener jsonTokener = new JSONTokener(IOUtils.toString(asdcServicesFile)); + final JSONObject sdcServicesCatalog = new JSONObject(jsonTokener); + + asdcClient = new LocalAsdcClient.Builder().catalog(sdcServicesCatalog).build(); + + } + + //@Test + public void assertEqualsBetweenServices() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Service expectedService = mockHelper.getNewServiceModel().getService(); + Service actualService = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService(); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService)); + } + } + + //@Test + public void assertEqualBetweenObjects() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + final Path csarPath = getCsarPath(mockHelper.getUuid()); + System.out.println("Comparing for csar " + csarPath); + ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid())); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel)); + } + } + + //@Test + public void assertEqualsBetweenNetworkNodes() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Map<String, Network> expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks(); + Map<String, Network> actualNetworksMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks(); + for (Map.Entry<String, Network> entry : expectedNetworksMap.entrySet()) { + Network expectedNetwork = entry.getValue(); + Network actualNetwork = actualNetworksMap.get(entry.getKey()); + Assert.assertEquals(expectedNetwork.getModelCustomizationName(), actualNetwork.getModelCustomizationName()); + verifyBaseNodeProperties(expectedNetwork, actualNetwork); + compareProperties(expectedNetwork.getProperties(), actualNetwork.getProperties()); + } + } + } + + //Because we are not supporting the old flow, the JSON are different by definition. + //@Test + public void assertEqualsBetweenVnfsOfTosca() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Map<String, VNF> expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs(); + Map<String, VNF> actualVnfsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs(); + for (Map.Entry<String, VNF> entry : expectedVnfsMap.entrySet()) { + VNF expectedVnf = entry.getValue(); + VNF actualVnf = actualVnfsMap.get(entry.getKey()); + verifyBaseNodeProperties(expectedVnf, actualVnf); + Assert.assertEquals(expectedVnf.getModelCustomizationName(), actualVnf.getModelCustomizationName()); + compareProperties(expectedVnf.getProperties(), actualVnf.getProperties()); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVnf), om.writeValueAsString(actualVnf)); + } + } + } + + //@Test + public void assertEqualsBetweenCollectionResourcesOfTosca() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Map<String, CR> expectedVnfsMap = mockHelper.getNewServiceModel().getCollectionResource(); + Map<String, CR> actualCRsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getCollectionResource(); + if(!actualCRsMap.isEmpty()) { + for (Map.Entry<String, CR> entry : expectedVnfsMap.entrySet()) { + CR expectedCR = entry.getValue(); + CR actualCR = actualCRsMap.get(entry.getKey()); + verifyCollectionResource(expectedCR, actualCR); + Assert.assertEquals(expectedCR.getName(), actualCR.getName()); + compareProperties(expectedCR.getProperties(), actualCR.getProperties()); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedCR), om.writeValueAsString(actualCR)); + } + } + } + } + + private void verifyCollectionResource(CR expectedCR, CR actualCR) { + verifyBaseNodeProperties(expectedCR, actualCR); + Assert.assertEquals(expectedCR.getCategory(), actualCR.getCategory()); + Assert.assertEquals(expectedCR.getSubcategory(), actualCR.getSubcategory()); + Assert.assertEquals(expectedCR.getResourceVendor(), actualCR.getResourceVendor()); + Assert.assertEquals(expectedCR.getResourceVendorRelease(), actualCR.getResourceVendorRelease()); + Assert.assertEquals(expectedCR.getResourceVendorModelNumber(), actualCR.getResourceVendorModelNumber()); + Assert.assertEquals(expectedCR.getCustomizationUUID(), actualCR.getCustomizationUUID()); + verifyNetworkCollections(expectedCR.getNetworksCollection(), actualCR.getNetworksCollection()); + } + + private void verifyNetworkCollections(Map<String, NetworkCollection> expectedNetworksCollection, Map<String, NetworkCollection> actualNetworksCollection) { + for (Map.Entry<String, NetworkCollection> property : expectedNetworksCollection.entrySet()) { + NetworkCollection expectedValue = property.getValue(); + String key = property.getKey(); + NetworkCollection actualValue = actualNetworksCollection.get(key); + verifyNetworkCollection(expectedValue, actualValue); + } + } + + private void verifyNetworkCollection(NetworkCollection expectedValue, NetworkCollection actualValue) { + Assert.assertEquals(expectedValue.getInvariantUuid(), actualValue.getInvariantUuid()); + Assert.assertEquals(expectedValue.getName(), actualValue.getName()); + Assert.assertEquals(expectedValue.getUuid(), actualValue.getUuid()); + Assert.assertEquals(expectedValue.getVersion(), actualValue.getVersion()); + Assert.assertEquals(expectedValue.getNetworkCollectionProperties().getNetworkCollectionDescription(), actualValue.getNetworkCollectionProperties().getNetworkCollectionDescription()); + Assert.assertEquals(expectedValue.getNetworkCollectionProperties().getNetworkCollectionFunction(), actualValue.getNetworkCollectionProperties().getNetworkCollectionFunction()); + } + + + //@Test + public void assertEqualsBetweenVolumeGroups() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Map<String, VolumeGroup> actualVolumeGroups = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVolumeGroups(); + Map<String, VolumeGroup> expectedVolumeGroups = mockHelper.getNewServiceModel().getVolumeGroups(); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVolumeGroups), om.writeValueAsString(actualVolumeGroups)); + } + } + + //@Test + public void assertEqualsBetweenVfModules() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Map<String, VfModule> actualVfModules = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVfModules(); + Map<String, VfModule> expectedVfModules = mockHelper.getNewServiceModel().getVfModules(); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVfModules), om.writeValueAsString(actualVfModules)); + } + } + + //@Test + public void assertEqualsBetweenPolicyConfigurationNodes() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Map<String, PortMirroringConfig> actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); + Map<String, PortMirroringConfig> expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); + JsonAssert.assertJsonEquals(actualConfigurations, expectedConfigurations); + } + } + //@Test + public void assertEqualsBetweenPolicyConfigurationByPolicyFalse() throws Exception { + ToscaParserMockHelper mockHelper = new ToscaParserMockHelper(Constants.configurationByPolicyFalseUuid, Constants.configurationByPolicyFalseFilePath); + InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(mockHelper.getFilePath()); + String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name()); + NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class); + mockHelper.setNewServiceModel(newServiceModel1); + Map<String, PortMirroringConfig> expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); + Map<String, PortMirroringConfig> actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); + + setPprobeServiceProxy(expectedConfigurations); + + JsonAssert.assertJsonEquals(expectedConfigurations, actualConfigurations); + } + + private void setPprobeServiceProxy(Map<String, PortMirroringConfig> expectedConfigurations){ + //Port Mirroring Configuration By Policy 0 doesn't contains pProbe. + // But due to sdc design if pProbe not exists parser expects to get it from other source. + // In a follow implementation provided the expected pProbe. + PortMirroringConfig pmconfig = expectedConfigurations.get("Port Mirroring Configuration By Policy 0"); + pmconfig.setCollectorNodes(new ArrayList<>(Arrays.asList("pprobeservice_proxy 4"))); + + } + //@Test + public void assertEqualsBetweenServiceProxyNodes() throws Exception { + for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { + Map<String, ServiceProxy> actualServiceProxies = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getServiceProxies(); + Map<String, ServiceProxy> expectedServiceProxies = mockHelper.getNewServiceModel().getServiceProxies(); + JsonAssert.assertJsonEquals(actualServiceProxies, expectedServiceProxies); + } + } + + private void verifyBaseNodeProperties(Node expectedNode, Node actualNode) { + Assert.assertEquals(expectedNode.getName(), actualNode.getName()); + Assert.assertEquals(expectedNode.getCustomizationUuid(), actualNode.getCustomizationUuid()); + Assert.assertEquals(expectedNode.getDescription(), actualNode.getDescription()); + Assert.assertEquals(expectedNode.getInvariantUuid(), actualNode.getInvariantUuid()); + Assert.assertEquals(expectedNode.getUuid(), actualNode.getUuid()); + Assert.assertEquals(expectedNode.getVersion(), actualNode.getVersion()); + } + + private void compareProperties(Map<String, String> expectedProperties, Map<String, String> actualProperties) { + for (Map.Entry<String, String> property : expectedProperties.entrySet()) { + String expectedValue = property.getValue(); + String key = property.getKey(); + String actualValue = actualProperties.get(key); + Assert.assertEquals(expectedValue, actualValue); + } + } + + private ToscaParserMockHelper[] getExpectedServiceModel() throws IOException { + ToscaParserMockHelper[] mockHelpers = { + new ToscaParserMockHelper(Constants.vlUuid, Constants.vlFilePath), + new ToscaParserMockHelper(Constants.vfUuid, Constants.vfFilePath), + new ToscaParserMockHelper(Constants.crUuid, Constants.crFilePath), + new ToscaParserMockHelper(Constants.vfWithAnnotationUuid, Constants.vfWithAnnotationFilePath), + new ToscaParserMockHelper(Constants.vfWithVfcGroup, Constants.vfWithVfcGroupFilePath), + new ToscaParserMockHelper(Constants.configurationUuid, Constants.configurationFilePath) + }; + for (ToscaParserMockHelper mockHelper : mockHelpers) { + InputStream jsonFile = this.getClass().getClassLoader().getResourceAsStream(mockHelper.getFilePath()); + System.out.println(jsonFile); + String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name()); + NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class); + mockHelper.setNewServiceModel(newServiceModel1); + } + return mockHelpers; + } + + + private Path getCsarPath(String uuid) throws AsdcCatalogException { + return asdcClient.getServiceToscaModel(UUID.fromString(uuid)); + } + + private org.onap.vid.asdc.beans.Service getServiceByUuid(String uuid) throws AsdcCatalogException { + return asdcClient.getService(UUID.fromString(uuid)); + } + + public class Constants { + public static final String configurationUuid = "ee6d61be-4841-4f98-8f23-5de9da846ca7"; + public static final String configurationFilePath = "policy-configuration-csar.JSON"; + static final String vfUuid = "48a52540-8772-4368-9cdb-1f124ea5c931"; + static final String vfWithAnnotationUuid = "f4d84bb4-a416-4b4e-997e-0059973630b9"; + static final String vlUuid = "cb49608f-5a24-4789-b0f7-2595473cb997"; + static final String crUuid = "76f27dfe-33e5-472f-8e0b-acf524adc4f0"; + static final String vfWithVfcGroup = "6bce7302-70bd-4057-b48e-8d5b99e686ca"; + // public static final String PNFUuid = "68101369-6f08-4e99-9a28-fa6327d344f3"; + static final String vfFilePath = "vf-csar.JSON"; + static final String vlFilePath = "vl-csar.JSON"; + static final String crFilePath = "cr-csar.JSON"; + static final String vfWithAnnotationFilePath = "vf-with-annotation-csar.json"; + static final String vfWithVfcGroupFilePath = "vf-with-vfcInstanceGroups.json"; + public static final String configurationByPolicyFalseUuid = "ee6d61be-4841-4f98-8f23-5de9da845544"; + public static final String configurationByPolicyFalseFilePath = "policy-configuration-by-policy-false.JSON"; - @Autowired - private WebApplicationContext wac; - @BeforeMethod - private void verifyWiring() { - Assert.assertNotNull(wac); - Assert.assertNotNull(toscaParserImpl2); } + + @Test - public void testGetNFModuleFromVf() throws Exception { + public void testGetNFModuleFromVf() { ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(); Map<String, VfModule> vfModulesFromVF = toscaParserImpl2.getVfModulesFromVF(csarHelper, myUUID); @@ -60,12 +292,10 @@ public class ToscaParserImpl2Test extends AbstractTestNGSpringContextTests { hasKey("withoutVol"), hasKey("withVol") )); - - verify(csarHelper, only()).getVfModulesByVf(anyString()); } @Test - public void testGetVolumeGroupsFromVF() throws Exception { + public void testGetVolumeGroupsFromVF() { ISdcCsarHelper csarHelper = getMockedSdcCsarHelper(); Map<String, VolumeGroup> volumeGroupsFromVF = toscaParserImpl2.getVolumeGroupsFromVF(csarHelper, myUUID); @@ -74,15 +304,11 @@ public class ToscaParserImpl2Test extends AbstractTestNGSpringContextTests { aMapWithSize(1), hasKey("withVol") )); - - verify(csarHelper, only()).getVfModulesByVf(anyString()); } private ISdcCsarHelper getMockedSdcCsarHelper() { ISdcCsarHelper csarHelper = mock(ISdcCsarHelper.class); -// ThreadLocalsHolder.setCollector(new ExceptionCollector("c:\\temp\\foo")); - Group withVol = createMinimalGroup("withVol", true); Group withoutVol = createMinimalGroup("withoutVol", false); @@ -115,11 +341,8 @@ public class ToscaParserImpl2Test extends AbstractTestNGSpringContextTests { customDef = new LinkedHashMap<>(); vfModule = addNewNamedMap(customDef, "org.onap.groups.VfModule"); vfModuleProperties = addNewNamedMap(vfModule, "properties"); -// vfModule.put("derived_from", "tosca.groups.Root"); -// vfModule.put("description", "Grouped all heat resources which are in the same VF Module"); volumeGroup = addNewNamedMap(vfModuleProperties, "volume_group"); -// volumeGroup.put("description", "volume_group"); volumeGroup.put("type", "boolean"); volumeGroup.put("default", false); volumeGroup.put("required", true); diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java index c1833bb7..75b84b2d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java @@ -1,225 +1,69 @@ package org.onap.vid.asdc.rest; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.onap.vid.testUtils.TestUtils; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; +import javax.ws.rs.NotFoundException; +import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; - -import org.junit.Before; -import org.junit.Test; -import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.beans.Artifact; -import org.onap.vid.asdc.beans.Resource; -import org.onap.vid.asdc.beans.Service; +import java.net.URI; +import java.util.UUID; +import java.util.function.Consumer; -import nu.xom.Builder; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; +import static org.testng.AssertJUnit.fail; public class RestfulAsdcClientTest { - private RestfulAsdcClient createTestSubject() { - return new RestfulAsdcClient.Builder(restClient, uri).auth(auth) - .build(); + @DataProvider + public static Object[][] javaxExceptions() { + + return new Object[][] { + {NotFoundException.class, (Consumer<Client>) javaxClientMock -> + when(javaxClientMock.target(any(URI.class))).thenThrow( + new NotFoundException("HTTP 404 Not Found"))}, + {ProcessingException.class, (Consumer<Client>) javaxClientMock -> + when(javaxClientMock.target(any(URI.class))).thenThrow( + new ProcessingException("java.net.ConnectException: Connection refused: connect"))}, + }; } - /** The rest client. */ - private Client restClient; - - /** The uri. */ - private URI uri; - - /** The properties. */ - private Properties properties; - - /** The auth. */ - private String auth; - - /** - * Sets the up. - * - * @throws URISyntaxException - * the URI syntax exception - * @throws IOException - * Signals that an I/O exception has occurred. - */ - @Before - public void setUp() throws URISyntaxException, IOException { - final InputStream propertiesFile = getClass().getClassLoader() - .getResourceAsStream("asdc.properties"); - properties = new Properties(); - properties.load(propertiesFile); + @Test(dataProvider = "javaxExceptions") + public void whenJavaxClientThrowException_thenExceptionRethrown(Class<? extends Throwable> expectedType, Consumer<Client> setupMocks) throws Exception { + /* + Call chain is like: + this test -> RestfulAsdcClient -> javax's Client - final String protocol = properties.getProperty("protocol", "http"); + In this test, *RestfulAsdcClient* is under test (actual implementation is used), while javax's Client is + mocked to return pseudo-responses or - better - throw exceptions. + */ - restClient = ClientBuilder.newBuilder() - .hostnameVerifier(new HostnameVerifier() { + // prepare mocks + TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); + Client javaxClientMock = mocks.getFakeClient(); - @Override - public boolean verify(String arg0, SSLSession arg1) { - return true; - } - }) + // prepare real RestfulAsdcClient (Under test) + RestfulAsdcClient restfulAsdcClient = new RestfulAsdcClient.Builder(javaxClientMock, new URI("")) + .auth("") .build(); - uri = new URI(protocol + "://" + properties.getProperty("host", "localhost") + ":" - + properties.getProperty("port", "80") + "/"); - auth = properties.getProperty("auth"); - } - - @Test - public void testGetResource() throws Exception { - RestfulAsdcClient testSubject; - UUID uuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - Resource result; - - // default test - testSubject = createTestSubject(); - try { - result = testSubject.getResource(uuid); - } catch (Exception e) { - - } - } - - @Test - public void testGetResourceArtifact() throws Exception { - RestfulAsdcClient testSubject; - UUID resourceUuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - UUID artifactUuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - Artifact result; - - // default test - testSubject = createTestSubject(); - try { - result = testSubject.getResourceArtifact(resourceUuid, artifactUuid); - } catch (Exception e) { - - } - } - - @Test - public void testGetResources() throws Exception { - RestfulAsdcClient testSubject; - Collection<Resource> result; - - // default test - testSubject = createTestSubject(); - try { - result = testSubject.getResources(); - } catch (Exception e) { - - } - } - - @Test - public void testGetResources_1() throws Exception { - RestfulAsdcClient testSubject; - Map<String, String[]> filter = null; - Collection<Resource> result; - - // default test - testSubject = createTestSubject(); - try { - result = testSubject.getResources(filter); - } catch (Exception e) { - - } - } - - @Test - public void testGetResourceToscaModel() throws Exception { - RestfulAsdcClient testSubject; - UUID resourceUuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - - // default test - testSubject = createTestSubject(); - try { - testSubject.getResourceToscaModel(resourceUuid); - } catch (Exception e) { - } - } + /// TEST: + setupMocks.accept(javaxClientMock); - @Test - public void testGetService() throws Exception { - RestfulAsdcClient testSubject; - UUID uuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - Service result; - - // default test - testSubject = createTestSubject(); try { - result = testSubject.getService(uuid); + restfulAsdcClient.getServiceToscaModel(UUID.randomUUID()); } catch (Exception e) { - + assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType)); + return; //OK } - } - - @Test - public void testGetServiceArtifact() throws Exception { - RestfulAsdcClient testSubject; - UUID serviceUuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - UUID artifactUuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - Artifact result; - - // default test - testSubject = createTestSubject(); - try { - result = testSubject.getServiceArtifact(serviceUuid, artifactUuid); - } catch (Exception e) { - - } - } - - @Test - public void testGetServices() throws Exception { - RestfulAsdcClient testSubject; - Collection<Service> result; - // default test - testSubject = createTestSubject(); - try { - result = testSubject.getServices(); - } catch (Exception e) { - - } - } - - @Test - public void testGetServices_1() throws Exception { - RestfulAsdcClient testSubject; - Map<String, String[]> filter = null; - Collection<Service> result; - - // default test - testSubject = createTestSubject(); - try { - result = testSubject.getServices(filter); - } catch (Exception e) { - - } - } - - @Test - public void testGetServiceToscaModel() throws Exception { - RestfulAsdcClient testSubject; - UUID serviceUuid = UUID.fromString("123e4567-e89b-12d3-a456-556642440000"); - - // default test - testSubject = createTestSubject(); - try { - testSubject.getServiceToscaModel(serviceUuid); - } catch (Exception e) { - - } + fail("exception shall rethrown by getServiceToscaModel once javax client throw exception "); } -}
\ No newline at end of file +} diff --git a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java index e19bcbc2..113b9f1f 100644 --- a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java @@ -57,6 +57,17 @@ public class AaiServiceTest { } @Test + public void testPnfByRegion(){ + AaiGetPnfResponse aaiGetPnfResponse = new AaiGetPnfResponse(); + AaiResponse<AaiGetPnfResponse> aaiResponse = new AaiResponse<>(aaiGetPnfResponse, "", 200); + Mockito.doReturn(aaiResponse).when(aaiClientInterface).getPNFData(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + AaiResponse<AaiGetPnfResponse> aaiGetPnfResponseWrapper = aaiService.getPNFData("1345667", "1345667", "1345667", "1345667", "1345667", "1345667", "1345667"); + assertNotNull(aaiGetPnfResponseWrapper); + aaiGetPnfResponse = aaiGetPnfResponseWrapper.getT(); + assertNotNull(aaiGetPnfResponse); + } + + @Test public void testGetAssociatedPnfs(){ ServiceRelationships serviceRelationships = createServiceRelationships(); AaiResponse<ServiceRelationships> aaiResponse = new AaiResponse<>(serviceRelationships, null, 200); @@ -129,7 +140,7 @@ public class AaiServiceTest { @Test(dataProvider = "getTenantsData") public void testGetTenants(String userGlobalCustomerId, String userServiceType, String userTenantName, String serviceGlobalCustomerId, String serviceServiceType, String serviceTenantName, String serviceTenantId, boolean expectedIsPermitted) { - GetTenantsResponse[] getTenantsResponses = new GetTenantsResponse[] {new GetTenantsResponse(null, null, serviceTenantName, serviceTenantId, false)}; + GetTenantsResponse[] getTenantsResponses = new GetTenantsResponse[] {new GetTenantsResponse(null, null, serviceTenantName, serviceTenantId, expectedIsPermitted)}; AaiResponse<GetTenantsResponse[]> aaiResponse = new AaiResponse<>(getTenantsResponses, null, 200); Mockito.doReturn(aaiResponse).when(aaiClientInterface).getTenants(serviceGlobalCustomerId, serviceServiceType); Role role = new Role(null, userGlobalCustomerId, userServiceType, userTenantName); diff --git a/vid-app-common/src/test/java/org/onap/vid/client/FakeHttpSessionTest.java b/vid-app-common/src/test/java/org/onap/vid/client/FakeHttpSessionTest.java deleted file mode 100644 index 74cfbcfc..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/client/FakeHttpSessionTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.onap.vid.client; - -import java.util.Enumeration; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpSessionContext; - -import org.junit.Test; - - -public class FakeHttpSessionTest { - - private FakeHttpSession createTestSubject() { - return new FakeHttpSession(); - } - - - @Test - public void testGetCreationTime() throws Exception { - FakeHttpSession testSubject; - long result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getCreationTime(); - } - - - @Test - public void testGetId() throws Exception { - FakeHttpSession testSubject; - String result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getId(); - } - - - @Test - public void testGetLastAccessedTime() throws Exception { - FakeHttpSession testSubject; - long result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getLastAccessedTime(); - } - - - @Test - public void testGetServletContext() throws Exception { - FakeHttpSession testSubject; - ServletContext result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getServletContext(); - } - - - @Test - public void testSetMaxInactiveInterval() throws Exception { - FakeHttpSession testSubject; - int maxInactiveInterval = 0; - - // default test - testSubject = createTestSubject(); - testSubject.setMaxInactiveInterval(maxInactiveInterval); - } - - - @Test - public void testGetMaxInactiveInterval() throws Exception { - FakeHttpSession testSubject; - int result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getMaxInactiveInterval(); - } - - - @Test - public void testGetSessionContext() throws Exception { - FakeHttpSession testSubject; - HttpSessionContext result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getSessionContext(); - } - - - @Test - public void testGetAttribute() throws Exception { - FakeHttpSession testSubject; - String name = ""; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAttribute(name); - } - - - @Test - public void testGetValue() throws Exception { - FakeHttpSession testSubject; - String name = ""; - Object result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValue(name); - } - - - @Test - public void testGetAttributeNames() throws Exception { - FakeHttpSession testSubject; - Enumeration<String> result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getAttributeNames(); - } - - - @Test - public void testGetValueNames() throws Exception { - FakeHttpSession testSubject; - String[] result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getValueNames(); - } - - - @Test - public void testSetAttribute() throws Exception { - FakeHttpSession testSubject; - String name = ""; - Object value = null; - - // default test - testSubject = createTestSubject(); - testSubject.setAttribute(name, value); - } - - - @Test - public void testPutValue() throws Exception { - FakeHttpSession testSubject; - String name = ""; - Object value = null; - - // default test - testSubject = createTestSubject(); - testSubject.putValue(name, value); - } - - - @Test - public void testRemoveAttribute() throws Exception { - FakeHttpSession testSubject; - String name = ""; - - // default test - testSubject = createTestSubject(); - testSubject.removeAttribute(name); - } - - - @Test - public void testRemoveValue() throws Exception { - FakeHttpSession testSubject; - String name = ""; - - // default test - testSubject = createTestSubject(); - testSubject.removeValue(name); - } - - - @Test - public void testInvalidate() throws Exception { - FakeHttpSession testSubject; - - // default test - testSubject = createTestSubject(); - testSubject.invalidate(); - } - - - @Test - public void testIsNew() throws Exception { - FakeHttpSession testSubject; - boolean result; - - // default test - testSubject = createTestSubject(); - result = testSubject.isNew(); - } -}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java new file mode 100644 index 00000000..eb9239e1 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java @@ -0,0 +1,81 @@ +package org.onap.vid.config; + + +import org.hibernate.SessionFactory; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import javax.sql.DataSource; +import java.util.Properties; + +@Configuration +@EnableTransactionManagement +public class DataSourceConfig { + + @Bean + @Autowired + public LocalSessionFactoryBean sessionFactory(DataSource dataSource) { + LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); + sessionFactory.setDataSource(dataSource); + //I used this class org.openecomp.portalsdk.core.conf.HibernateConfiguration to learn how to config the session factory + // and use the following url for actual h2 properties + //https://github.com/levi-putna/Hibernate-H2-Example/blob/master/hibernate-h2-example/src/hibernate.cfg.xml + Properties properties = getH2Properties(); + + properties.put("hibernate.default_schema", "PUBLIC"); + properties.put("connection.pool_size", 10); + properties.put("cache.provider_class", "org.hibernate.cache.internal.NoCacheProvider"); + properties.put("hibernate.show_sql", false); + properties.put("hbm2ddl.auto", "create"); + properties.put("hibernate.hbm2ddl.auto", "create"); + + sessionFactory.setHibernateProperties(properties); + sessionFactory.setPackagesToScan("org.onap"); + return sessionFactory; + } + + @Bean + public DataSource getDataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.h2.Driver"); + dataSource.setUrl("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1"); + dataSource.setUsername("sa"); + dataSource.setPassword(""); + return dataSource; + } + + public Properties getH2Properties() { + Properties properties = new Properties(); + properties.put("dialect", "org.hibernate.dialect.H2Dialect"); + return properties; + } + + public Properties getSqliteProperties() { + Properties properties = new Properties(); + properties.put("connection.driver_class", "org.sqlite.JDBC"); + properties.put("connection.url", "jdbc:sqlite:memory:myDb"); + properties.put("connection.username", "sa"); + properties.put("connection.password", "sa"); + properties.put("dialect", "com.enigmabridge.hibernate.dialect.SQLiteDialect"); + return properties; + } + + @Bean + public DataAccessService dataAccessService() { + return new DataAccessServiceImpl(); + } + + @Bean + @Autowired + public PlatformTransactionManager transactionManager(SessionFactory sessionFactory) { + return new HibernateTransactionManager(sessionFactory); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/config/JobAdapterConfig.java b/vid-app-common/src/test/java/org/onap/vid/config/JobAdapterConfig.java new file mode 100644 index 00000000..7b999b40 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/config/JobAdapterConfig.java @@ -0,0 +1,33 @@ +package org.onap.vid.config; + + +import org.hibernate.SessionFactory; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.impl.JobAdapterImpl; +import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; +import org.onap.vid.properties.VidProperties; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +@Configuration +@EnableTransactionManagement +public class JobAdapterConfig { + + @Bean + public JobAdapter jobAdapter() { + return new JobAdapterImpl(); + } + + @Bean + public JobsBrokerService jobsBrokerService(DataAccessService dataAccessService, SessionFactory sessionFactory) { + int maxOpenedInstantiationRequestsToMso = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_MAX_OPENED_INSTANTIATION_REQUESTS)); + int pollingIntervalSeconds = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_ASYNC_POLLING_INTERVAL_SECONDS)); + + return new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, maxOpenedInstantiationRequestsToMso, pollingIntervalSeconds); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java new file mode 100644 index 00000000..245623aa --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java @@ -0,0 +1,90 @@ +package org.onap.vid.config; + +import org.hibernate.SessionFactory; +import org.mockito.Mockito; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.command.InProgressStatusCommand; +import org.onap.vid.job.command.JobCommandFactory; +import org.onap.vid.job.command.ServiceInstantiationCommand; +import org.onap.vid.job.impl.JobAdapterImpl; +import org.onap.vid.job.impl.JobWorker; +import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AsyncInstantiationBusinessLogicImpl; +import org.onap.vid.services.AuditService; +import org.onap.vid.services.AuditServiceImpl; +import org.onap.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Scope; +import org.togglz.core.manager.FeatureManager; + +@Configuration +public class JobCommandsConfigWithMockedMso { + + @Bean + public RestMsoImplementation restMso() { + return Mockito.mock(RestMsoImplementation.class); + } + + @Bean + public JobsBrokerService jobsBrokerService(DataAccessService dataAccessService, SessionFactory sessionFactory) { + return new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0); + } + + @Bean + public HttpsAuthClient httpsAuthClientFactory(){ + return new HttpsAuthClient("some random path"); + } + + @Bean + public JobAdapter jobAdapter() { + return new JobAdapterImpl(); + } + + @Bean + public JobCommandFactory jobCommandFactory(ApplicationContext applicationContext) { + return new JobCommandFactory(applicationContext); + } + + @Bean + public JobWorker jobWorker(JobsBrokerService jobsBrokerService, JobCommandFactory jobCommandFactory) { + JobWorker jobWorker = new JobWorker(); + jobWorker.setJobsBrokerService(jobsBrokerService); + jobWorker.setJobCommandFactory(jobCommandFactory); + return jobWorker; + } + + @Bean + public AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic(DataAccessService dataAccessService, + JobAdapter jobAdapter, + JobsBrokerService jobsBrokerService, + SessionFactory sessionFactory, + AaiClientInterface aaiClient) { + return new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public ServiceInstantiationCommand serviceInstantiationCommand() { + return new ServiceInstantiationCommand(); + } + + @Bean + @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) + public InProgressStatusCommand inProgressStatusCommand() { + return new InProgressStatusCommand(); + } + + @Bean + public AuditService auditService() { + return new AuditServiceImpl(); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/config/MockedAaiClientAndFeatureManagerConfig.java b/vid-app-common/src/test/java/org/onap/vid/config/MockedAaiClientAndFeatureManagerConfig.java new file mode 100644 index 00000000..1a4eb528 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/config/MockedAaiClientAndFeatureManagerConfig.java @@ -0,0 +1,21 @@ +package org.onap.vid.config; + +import org.mockito.Mockito; +import org.onap.vid.aai.AaiClientInterface; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.togglz.core.manager.FeatureManager; + +@Configuration +public class MockedAaiClientAndFeatureManagerConfig { + + @Bean + public FeatureManager featureManager() { + return Mockito.mock(FeatureManager.class); + } + + @Bean + public AaiClientInterface aaiClient() { + return Mockito.mock(AaiClientInterface.class); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java new file mode 100644 index 00000000..4076b3de --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java @@ -0,0 +1,60 @@ +package org.onap.vid.controller; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.AaiResponseTranslator; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk; +import org.onap.vid.controllers.AaiController; +import org.onap.vid.services.AaiService; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Map; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; + + +public class AaiControllerTest { + + @InjectMocks + AaiController aaiController = new AaiController(); + + @Mock + AaiService aaiService; + + @BeforeMethod + public void initMocks(){ + MockitoAnnotations.initMocks(this); + } + + @Test + public void getPortMirroringConfigData_givenThreeIds_ReturnsThreeResults() { + + final PortMirroringConfigDataOk toBeReturnedForA = new PortMirroringConfigDataOk("foobar"); + final PortMirroringConfigDataError toBeReturnedForB = new PortMirroringConfigDataError("foo", "{ baz: qux }"); + final PortMirroringConfigDataOk toBeReturnedForC = new PortMirroringConfigDataOk("corge"); + + Mockito + .doReturn(toBeReturnedForA) + .doReturn(toBeReturnedForB) + .doReturn(toBeReturnedForC) + .when(aaiService).getPortMirroringConfigData(Mockito.anyString()); + + final Map<String, AaiResponseTranslator.PortMirroringConfigData> result = aaiController.getPortMirroringConfigsData(ImmutableList.of("a", "b", "c")); + + assertThat(result, is(ImmutableMap.of( + "a", toBeReturnedForA, + "b", toBeReturnedForB, + "c", toBeReturnedForC + ))); + } + + + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java new file mode 100644 index 00000000..61f18f54 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ClientCredentialsFilterTest.java @@ -0,0 +1,92 @@ +package org.onap.vid.controller; + + +import org.junit.Assert; +import org.mockito.Mockito; +import org.onap.vid.controller.filter.ClientCredentialsFilter; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +import static org.mockito.Matchers.any; + + +/** + * Created by amichai on 16/05/2018. + */ +@Test +public class ClientCredentialsFilterTest { + + @DataProvider + public static Object[][] authorizedData() { + return new Object[][] { + {"Basic 123==", null}, + {null, null}, + {null, ""}, + {"Basic 123==", ""}, + {"Basic 123==", "Basic 123=="} + }; + } + + @DataProvider + public static Object[][] notAuthorizedData() { + return new Object[][] { + {null, "Basic 123=="}, + {"", "Basic 123=="}, + {"not null but not as expected", "Basic 123=="}, + {"basic 123==", "Basic 123=="} + }; + } + + @DataProvider + public static Object[][] clientVerified() { + return new Object[][] { + {true}, + {false} + }; + } + + @Test(dataProvider = "authorizedData") + public void givenAuthorizationHeader_Authorized(String actualAuth, String expectedAuth){ + ClientCredentialsFilter filter = new ClientCredentialsFilter(); + Assert.assertTrue(filter.verifyClientCredentials(actualAuth, expectedAuth)); + } + + @Test(dataProvider = "notAuthorizedData") + public void givenAuthorizationHeader_NotAuthorized(String actualAuth, String expectedAuth){ + ClientCredentialsFilter filter = new ClientCredentialsFilter(); + Assert.assertFalse(filter.verifyClientCredentials(actualAuth, expectedAuth)); + } + + //@Test(dataProvider = "clientVerified") + public void notAuthorized_return401(Boolean clientVerified) throws IOException, ServletException { + ClientCredentialsFilter filter = Mockito.mock(ClientCredentialsFilter.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + FilterChain chain = Mockito.mock(FilterChain.class); + + + Mockito.when(filter.verifyClientCredentials(any(String.class),any(String.class))).thenReturn(clientVerified); + Mockito.doNothing().when(response).sendError(401); + + Mockito.doCallRealMethod().when(filter).doFilter(request,response,chain); + filter.doFilter(request,response,chain); + + if (clientVerified) + { + Mockito.verify(chain).doFilter(request,response); + + } + else { + Mockito.verify(response).sendError(401); + } + + } + + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java new file mode 100644 index 00000000..54d0d77b --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java @@ -0,0 +1,79 @@ +package org.onap.vid.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.vid.aai.AaiClient; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.AaiResponseTranslator; +import org.onap.vid.aai.model.PortDetailsTranslator; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.asdc.AsdcClient; +import org.onap.vid.asdc.parser.ToscaParserImpl2; +import org.onap.vid.services.AaiService; +import org.onap.vid.services.AaiServiceImpl; +import org.onap.vid.services.VidService; +import org.onap.vid.services.VidServiceImpl; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.togglz.core.manager.FeatureManager; + +import javax.servlet.ServletContext; +import java.io.File; + +@Configuration +public class LocalWebConfig { + + /** + * Gets the object mapper. + * + * @return the object mapper + */ + @Bean + public ObjectMapper getObjectMapper() { + return new ObjectMapper(); + } + + + @Bean + public VidService vidService(AsdcClient asdcClient, FeatureManager featureManager) { + return new VidServiceImpl(asdcClient, featureManager); + } + + @Bean + public AaiService getAaiService() { + return new AaiServiceImpl(); + } + + @Bean + public HttpsAuthClient httpsAuthClientFactory(ServletContext servletContext) { + final String certFilePath = new File(servletContext.getRealPath("/WEB-INF/cert/")).getAbsolutePath(); + return new HttpsAuthClient(certFilePath); + } + + @Bean(name = "aaiRestInterface") + public AAIRestInterface aaiRestInterface(HttpsAuthClient httpsAuthClientFactory) { + return new AAIRestInterface(httpsAuthClientFactory); + } + + @Bean + public AaiClientInterface getAaiClientInterface(@Qualifier("aaiRestInterface")AAIRestInterface aaiRestInterface, PortDetailsTranslator portDetailsTranslator) { + return new AaiClient(aaiRestInterface, portDetailsTranslator); + } + + @Bean + public ToscaParserImpl2 getToscaParser() { + return new ToscaParserImpl2(); + } + + @Bean + public AaiResponseTranslator aaiResponseTranslator() { + return new AaiResponseTranslator(); + } + + @Bean + public PortDetailsTranslator portDetailsTranslator(){ + return new PortDetailsTranslator(); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java new file mode 100644 index 00000000..4645a83a --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java @@ -0,0 +1,109 @@ +package org.onap.vid.controller; + +import org.apache.commons.lang.StringEscapeUtils; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.controllers.MsoConfig; +import org.onap.vid.controllers.MsoController; +import org.onap.vid.domain.mso.RequestInfo; +import org.onap.vid.factories.MsoRequestFactory; +import org.onap.vid.mso.rest.Request; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.Task; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +import org.springframework.test.context.web.WebAppConfiguration; +import org.testng.Assert; +import org.testng.Assert.*; +import org.testng.annotations.Test; + +import java.util.List; + + +@WebAppConfiguration +@ContextConfiguration(classes = {SystemProperties.class, MsoConfig.class}) +public class MsoControllerTest extends AbstractTestNGSpringContextTests { + + @Autowired + MsoRequestFactory msoRequestFactory; + + @Test(enabled = false) + public void testInstanceCreationNew() throws Exception { + + RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); + MsoController msoController = new MsoController(null); + //TODO: make ths test to really test something + //ResponseEntity<String> responseEntityNew = msoController.createSvcInstanceNew(null, requestDetails); + ResponseEntity<String> responseEntity = msoController.createSvcInstance(null, requestDetails); + //Assert.assertEquals(responseEntityNew, responseEntity); + + } + + @Test(enabled = false) + public void testInstanceCreationLocalWithRest() throws Exception { + + RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); + MsoController msoController = new MsoController(null); + ResponseEntity<String> responseEntityNew = msoController.createSvcInstance(null, requestDetails); + //TODO: make ths test to really test something +// ResponseEntity<String> responseEntityRest = msoController.createSvcInstanceNewRest(null, requestDetails); +// +// Assert.assertEquals(responseEntityNew.getBody(), responseEntityRest.getBody()); + + } + + @Test(enabled = false) + public void testInstanceCreation() throws Exception { + + RequestDetails requestDetails = msoRequestFactory.createMsoRequest("msoRequest.json"); + MsoController msoController = new MsoController(null); + ResponseEntity<String> responseEntity = msoController.createSvcInstance(null, requestDetails); + + + Assert.assertEquals(responseEntity.getBody(), "{ \"status\": 200, \"entity\": {\n" + + " \"requestReferences\": {\n" + + " \"instanceId\": \"ba00de9b-3c3e-4b0a-a1ad-0c5489e711fb\",\n" + + " \"requestId\": \"311cc766-b673-4a50-b9c5-471f68914586\"\n" + + " }\n" + + "}}"); + + } + + @Test(enabled = false) + public void testGetOrchestrationRequestsForDashboard() throws Exception { + MsoController msoController = new MsoController(null); + List<Request> orchestrationRequestsForDashboard = msoController.getOrchestrationRequestsForDashboard(); + + Assert.assertEquals(orchestrationRequestsForDashboard.size(), 2); + } + + @Test(enabled = false) + public void testGetManualTasksByRequestId() throws Exception { + MsoController msoController = new MsoController(null); + List<Task> orchestrationRequestsForDashboard = msoController.getManualTasksByRequestId("za1234d1-5a33-55df-13ab-12abad84e335"); + + Assert. assertEquals(orchestrationRequestsForDashboard.get(0).getTaskId(), "daf4dd84-b77a-42da-a051-3239b7a9392c"); + } + + + public void testCompleteManualTask() throws Exception { // TODO not done yet + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setResponseValue("rollback"); + requestInfo.setRequestorId("abc"); + requestInfo.setSource("VID"); + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setRequestInfo(requestInfo); + MsoController msoController = new MsoController(null); + ResponseEntity<String> responseEntity = msoController.manualTaskComplete("daf4dd84-b77a-42da-a051-3239b7a9392c", requestDetails); + String assertString = "{ \\\"status\\\": 200, \\\"entity\\\": {\\n\" +\n" + + " \" \\\"taskRequestReference\\\": {\\n\" +\n" + + " \" \\\"taskId\\\": \\\"daf4dd84-b77a-42da-a051-3239b7a9392c\\\"\\n\" +\n" + + " \" }\\n\" +\n" + + " \"}\\n\" +\n" + + " \"}"; + Assert.assertEquals(responseEntity.getBody(), StringEscapeUtils.unescapeJava(assertString)); + } + + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/PromiseEcompRequestIdFilterTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/PromiseEcompRequestIdFilterTest.java new file mode 100644 index 00000000..3bcb2d00 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/PromiseEcompRequestIdFilterTest.java @@ -0,0 +1,168 @@ +package org.onap.vid.controller; + +import com.google.common.collect.ImmutableMap; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.mockito.stubbing.Answer; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter; +import org.springframework.mock.web.MockHttpServletResponse; +import org.testng.annotations.Test; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.*; +import java.util.function.Function; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.onap.portalsdk.core.util.SystemProperties.ECOMP_REQUEST_ID; + +@Test +public class PromiseEcompRequestIdFilterTest { + + private final String anotherHeader = "ANDREI_RUBLEV"; + private final String anotherValue = "foo value"; + private final String mixedCaseHeader = "x-ecomp-REQUESTID"; + + @Test + public void givenRequestIdHeader_headerValueNotChanged() throws IOException, ServletException { + + final String someTxId = "863850e2-8545-4efd-94b8-afba5f52b3d5"; + + final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of( + anotherHeader, anotherValue, + ECOMP_REQUEST_ID, someTxId + ); + + buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId)); + } + + @Test + public void givenMixedCaseRequestIdHeader_headerValueNotChanged() throws IOException, ServletException { + + final String someTxId = "729bbd8d-b0c2-4809-a794-dcccd9cda2c0"; + + final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of( + mixedCaseHeader, someTxId, + anotherHeader, anotherValue + ); + + buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, specificTxId(someTxId)); + } + + @Test + public void givenNoRequestIdHeader_headerValueWasGenerated() throws IOException, ServletException { + + final ImmutableMap<String, String> incomingRequestHeaders = ImmutableMap.of( + anotherHeader, anotherValue + ); + + buildRequestThenRunThroughFilterAndAssertResultRequestHeaders(incomingRequestHeaders, UserUtils::getRequestId); + } + + + private void buildRequestThenRunThroughFilterAndAssertResultRequestHeaders( + ImmutableMap<String, String> originalRequestHeaders, + Function<HttpServletRequest, String> txIdExtractor + ) throws IOException, ServletException { + HttpServletRequest servletRequest = createMockedHttpServletRequest(originalRequestHeaders); + HttpServletResponse servletResponse = createMockedHttpServletResponse(); + + final FilterChain capturingFilterChain = Mockito.mock(FilterChain.class); + + ////////////////// + // + // doFilter() is the function under test + // + new PromiseEcompRequestIdFilter().doFilter(servletRequest, servletResponse, capturingFilterChain); + // + ////////////////// + + final ServletRequest capturedServletRequest = extractCapturedServletRequest(capturingFilterChain); + final ServletResponse capturedServletResponse = extractCapturedServletResponse(capturingFilterChain); + final String expectedTxId = txIdExtractor.apply((HttpServletRequest) capturedServletRequest); + + assertRequestObjectHeaders(capturedServletRequest, expectedTxId); + assertResponseObjectHeaders(capturedServletResponse, expectedTxId); + } + + + private void assertRequestObjectHeaders(ServletRequest request, String expectedTxId) { + /* + Assert that: + - Two headers are in place + - Direct value extraction is as expected + - UserUtils.getRequestId() returns correct and valid value + */ + final HttpServletRequest httpServletRequest = (HttpServletRequest) request; + + assertThat(Collections.list(httpServletRequest.getHeaderNames()), + containsInAnyOrder(equalToIgnoringCase(ECOMP_REQUEST_ID), equalToIgnoringCase(anotherHeader))); + + assertThat(httpServletRequest.getHeader(anotherHeader), is(anotherValue)); + + assertThat(httpServletRequest.getHeader(ECOMP_REQUEST_ID), is(expectedTxId)); + assertThat(httpServletRequest.getHeader(mixedCaseHeader), is(expectedTxId)); + + assertThat(UserUtils.getRequestId(httpServletRequest), is(expectedTxId)); + assertThat(UserUtils.getRequestId(httpServletRequest), is(not(emptyOrNullString()))); + } + + private void assertResponseObjectHeaders(ServletResponse response, String txId) { + final String REQUEST_ID_HEADER_NAME_IN_RESPONSE = mixedCaseHeader + "-echo"; + final HttpServletResponse httpServletResponse = (HttpServletResponse) response; + + assertThat("header " + REQUEST_ID_HEADER_NAME_IN_RESPONSE.toLowerCase() + " in response must be provided", + httpServletResponse.getHeader(REQUEST_ID_HEADER_NAME_IN_RESPONSE), is(txId)); + } + + + + private HttpServletRequest createMockedHttpServletRequest(Map<String, String> requestHeaders) { + HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); + requestHeaders.forEach((k, v) -> { + Mockito.when(servletRequest.getHeader(argThat(equalToIgnoringCase(k)))).thenReturn(v); + Mockito.when(servletRequest.getHeaders(argThat(equalToIgnoringCase(k)))).then(returnEnumerationAnswer(v)); + }); + Mockito.when(servletRequest.getHeaderNames()).then(returnEnumerationAnswer(requestHeaders.keySet())); + return servletRequest; + } + + private HttpServletResponse createMockedHttpServletResponse() { + return new MockHttpServletResponse(); + } + + private static Answer<Enumeration<String>> returnEnumerationAnswer(String ... items) { + return returnEnumerationAnswer(Arrays.asList(items)); + } + + private static Answer<Enumeration<String>> returnEnumerationAnswer(Collection<String> items) { + return invocation -> Collections.enumeration(items); + } + + private Function<HttpServletRequest, String> specificTxId(String someTxId) { + return r -> someTxId; + } + + private ServletRequest extractCapturedServletRequest(FilterChain capturingFilterChain) throws IOException, ServletException { + ArgumentCaptor<ServletRequest> captor = ArgumentCaptor.forClass(ServletRequest.class); + Mockito.verify(capturingFilterChain).doFilter(captor.capture(), any()); + return captor.getValue(); + } + + private ServletResponse extractCapturedServletResponse(FilterChain capturingFilterChain) throws IOException, ServletException { + ArgumentCaptor<ServletResponse> captor = ArgumentCaptor.forClass(ServletResponse.class); + Mockito.verify(capturingFilterChain).doFilter(any(), captor.capture()); + return captor.getValue(); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java new file mode 100644 index 00000000..36a17910 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java @@ -0,0 +1,42 @@ +package org.onap.vid.controller; + +import org.onap.vid.model.NewServiceModel; + +/** + * Created by moriya1 on 04/07/2017. + */ +public class ToscaParserMockHelper { + + private String uuid; + private String filePath; + private NewServiceModel newServiceModel; + + public ToscaParserMockHelper(String uuid, String filePath) { + this.uuid = uuid; + this.filePath = filePath; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public NewServiceModel getNewServiceModel() { + return newServiceModel; + } + + public void setNewServiceModel(NewServiceModel newServiceModel) { + this.newServiceModel = newServiceModel; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java index 2e2bc11e..317bd978 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java @@ -21,7 +21,7 @@ import org.springframework.web.multipart.MultipartFile; public class ChangeManagementControllerTest { private ChangeManagementController createTestSubject() { - return new ChangeManagementController(new WorkflowServiceImpl(), new ChangeManagementServiceImpl(null, null), + return new ChangeManagementController(new WorkflowServiceImpl(), new ChangeManagementServiceImpl(null, null, null), null); } diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java index d87fab47..59fed334 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/controllers/LocalWebConfig.java @@ -36,7 +36,7 @@ public class LocalWebConfig { @Bean public VidService vidService(AsdcClient asdcClient) { - return new VidServiceImpl(asdcClient); + return new VidServiceImpl(asdcClient, null); } @Bean @@ -46,7 +46,7 @@ public class LocalWebConfig { @Bean public AaiClientInterface getAaiClientInterface() { - return new AaiClient(); + return new AaiClient(null,null); } @Bean diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java index c138740e..d1e09ce8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controllers/MsoControllerNewTest.java @@ -7,13 +7,14 @@ import javax.servlet.http.HttpServletRequest; import org.junit.Test; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.mso.rest.RequestDetailsWrapper; import org.springframework.http.ResponseEntity; public class MsoControllerNewTest { private MsoController createTestSubject() { try { - return new MsoController(new MsoBusinessLogicImpl(null)); + return new MsoController(new MsoBusinessLogicImpl(null,null)); } catch (Exception e) { return null; } @@ -105,7 +106,7 @@ public class MsoControllerNewTest { MsoController testSubject; String serviceInstanceId = ""; HttpServletRequest request = null; - RequestDetails mso_request = null; + RequestDetailsWrapper mso_request = null; ResponseEntity<String> result; // default test @@ -122,12 +123,12 @@ public class MsoControllerNewTest { String serviceInstanceId = ""; HttpServletRequest request = null; RequestDetails mso_request = null; - ResponseEntity<String> result; + String result; // default test try { testSubject = createTestSubject(); - result = testSubject.deleteSvcInstance(serviceInstanceId, request, mso_request); + result = testSubject.deleteSvcInstance(serviceInstanceId, request, mso_request, ""); } catch (Exception e) { } } @@ -154,7 +155,7 @@ public class MsoControllerNewTest { MsoController testSubject; String serviceInstanceId = ""; String configurationId = ""; - RequestDetails mso_request = null; + RequestDetailsWrapper mso_request = null; ResponseEntity<String> result; // default test diff --git a/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java index 6125107f..4e2d994e 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controllers/VidControllerTest.java @@ -1,189 +1,189 @@ package org.onap.vid.controllers; -import com.fasterxml.jackson.databind.ObjectMapper; -import net.javacrumbs.jsonunit.JsonAssert; -import org.apache.commons.io.IOUtils; -import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.parser.ToscaParserImpl2; -import org.onap.vid.model.*; -import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockServletContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.web.WebAppConfiguration; -import org.testng.Assert; -import org.testng.annotations.Test; - -import static org.onap.vid.testUtils.TestUtils.assertJsonStringEqualsIgnoreNulls; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Path; -import java.util.Map; -import java.util.UUID; - -//import org.junit.Assert; -//import org.junit.Ignore; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) -//@RunWith(SpringJUnit4ClassRunner.class) -@WebAppConfiguration - -public class VidControllerTest extends AbstractTestNGSpringContextTests { - - @Autowired - MockServletContext context; - @Autowired - private AsdcClient asdcClient; - private ToscaParserImpl2 p2 = new ToscaParserImpl2(); - private ObjectMapper om = new ObjectMapper(); - - - @Test - public void assertEqualsBetweenServices() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Service expectedService = mockHelper.getNewServiceModel().getService(); - Service actualService = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService(); - assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService)); - } - } - +//import com.fasterxml.jackson.databind.ObjectMapper; +//import net.javacrumbs.jsonunit.JsonAssert; +//import org.apache.commons.io.IOUtils; +//import org.onap.vid.asdc.AsdcCatalogException; +//import org.onap.vid.asdc.AsdcClient; +//import org.onap.vid.asdc.parser.ToscaParserImpl2; +//import org.onap.vid.model.*; +//import org.onap.portalsdk.core.util.SystemProperties; +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.mock.web.MockServletContext; +//import org.springframework.test.context.ContextConfiguration; +//import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +//import org.springframework.test.context.web.WebAppConfiguration; +//import org.testng.Assert; +//import org.testng.annotations.Test; +// +//import static org.onap.vid.testUtils.TestUtils.assertJsonStringEqualsIgnoreNulls; +// +//import java.io.IOException; +//import java.io.InputStream; +//import java.nio.file.Path; +//import java.util.Map; +//import java.util.UUID; +// +////import org.junit.Assert; +////import org.junit.Ignore; +////import org.junit.Test; +////import org.junit.runner.RunWith; +////import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +// +//@ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) +////@RunWith(SpringJUnit4ClassRunner.class) +//@WebAppConfiguration +// +//public class VidControllerTest extends AbstractTestNGSpringContextTests { +// +// @Autowired +// MockServletContext context; +// @Autowired +// private AsdcClient asdcClient; +// private ToscaParserImpl2 p2 = new ToscaParserImpl2(); +// private ObjectMapper om = new ObjectMapper(); +// +// // @Test -// public void assertEqualBetweenObjects() throws Exception { +// public void assertEqualsBetweenServices() throws Exception { // for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { -// final Path csarPath = getCsarPath(mockHelper.getUuid()); -// System.out.println("Comparing for csar " + csarPath); -// ServiceModel actualServiceModel = p2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid())); -// assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel)); +// Service expectedService = mockHelper.getNewServiceModel().getService(); +// Service actualService = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService(); +// assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService)); // } // } - +// +//// @Test +//// public void assertEqualBetweenObjects() throws Exception { +//// for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { +//// final Path csarPath = getCsarPath(mockHelper.getUuid()); +//// System.out.println("Comparing for csar " + csarPath); +//// ServiceModel actualServiceModel = p2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid())); +//// assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel)); +//// } +//// } +// +//// @Test +//// public void assertEqualsBetweenNetworkNodes() throws Exception { +//// for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { +//// Map<String, Network> expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks(); +//// Map<String, Network> actualNetworksMap = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks(); +//// for (Map.Entry<String, Network> entry : expectedNetworksMap.entrySet()) { +//// Network expectedNetwork = entry.getValue(); +//// Network actualNetwork = actualNetworksMap.get(entry.getKey()); +//// Assert.assertEquals(expectedNetwork.getModelCustomizationName(), actualNetwork.getModelCustomizationName()); +//// verifyBaseNodeProperties(expectedNetwork, actualNetwork); +//// compareProperties(expectedNetwork.getProperties(), actualNetwork.getProperties()); +//// } +//// } +//// } +// +// //Because we are not supporting the old flow, the JSON are different by definition. // @Test -// public void assertEqualsBetweenNetworkNodes() throws Exception { +// public void assertEqualsBetweenVnfsOfTosca() throws Exception { // for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { -// Map<String, Network> expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks(); -// Map<String, Network> actualNetworksMap = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks(); -// for (Map.Entry<String, Network> entry : expectedNetworksMap.entrySet()) { -// Network expectedNetwork = entry.getValue(); -// Network actualNetwork = actualNetworksMap.get(entry.getKey()); -// Assert.assertEquals(expectedNetwork.getModelCustomizationName(), actualNetwork.getModelCustomizationName()); -// verifyBaseNodeProperties(expectedNetwork, actualNetwork); -// compareProperties(expectedNetwork.getProperties(), actualNetwork.getProperties()); +// Map<String, VNF> expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs(); +// Map<String, VNF> actualVnfsMap = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs(); +// for (Map.Entry<String, VNF> entry : expectedVnfsMap.entrySet()) { +// VNF expectedVnf = entry.getValue(); +// VNF actualVnf = actualVnfsMap.get(entry.getKey()); +// //need to uncomment these after 1806 merge +// //verifyBaseNodeProperties(expectedVnf, actualVnf); +// Assert.assertEquals(expectedVnf.getModelCustomizationName(), actualVnf.getModelCustomizationName()); +// //compareProperties(expectedVnf.getProperties(), actualVnf.getProperties()); +// //assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVnf), om.writeValueAsString(actualVnf)); // } // } // } - - //Because we are not supporting the old flow, the JSON are different by definition. - @Test - public void assertEqualsBetweenVnfsOfTosca() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Map<String, VNF> expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs(); - Map<String, VNF> actualVnfsMap = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs(); - for (Map.Entry<String, VNF> entry : expectedVnfsMap.entrySet()) { - VNF expectedVnf = entry.getValue(); - VNF actualVnf = actualVnfsMap.get(entry.getKey()); - //need to uncomment these after 1806 merge - //verifyBaseNodeProperties(expectedVnf, actualVnf); - Assert.assertEquals(expectedVnf.getModelCustomizationName(), actualVnf.getModelCustomizationName()); - //compareProperties(expectedVnf.getProperties(), actualVnf.getProperties()); - //assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVnf), om.writeValueAsString(actualVnf)); - } - } - } - - @Test - public void assertEqualsBetweenVolumeGroups() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Map<String, VolumeGroup> actualVolumeGroups = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVolumeGroups(); - Map<String, VolumeGroup> expectedVolumeGroups = mockHelper.getNewServiceModel().getVolumeGroups(); - JsonAssert.assertJsonEquals(actualVolumeGroups, expectedVolumeGroups); - } - } - - @Test - public void assertEqualsBetweenVfModules() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Map<String, VfModule> actualVfModules = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVfModules(); - Map<String, VfModule> expectedVfModules = mockHelper.getNewServiceModel().getVfModules(); - //need to uncomment after 1906 merge - //JsonAssert.assertJsonEquals(actualVfModules, expectedVfModules); - } - } - - /*@Test - public void assertEqualsBetweenPolicyConfigurationNodes() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Map<String, PortMirroringConfig> actualConfigurations = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); - Map<String, PortMirroringConfig> expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); - JsonAssert.assertJsonEquals(actualConfigurations, expectedConfigurations); - } - }*/ - - @Test - public void assertEqualsBetweenServiceProxyNodes() throws Exception { - for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { - Map<String, ServiceProxy> actualServiceProxies = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getServiceProxies(); - Map<String, ServiceProxy> expectedServiceProxies = mockHelper.getNewServiceModel().getServiceProxies(); - JsonAssert.assertJsonEquals(actualServiceProxies, expectedServiceProxies); - } - } - - private void verifyBaseNodeProperties(Node expectedNode, Node actualNode) { - Assert.assertEquals(expectedNode.getName(), actualNode.getName()); - Assert.assertEquals(expectedNode.getCustomizationUuid(), actualNode.getCustomizationUuid()); - Assert.assertEquals(expectedNode.getDescription(), actualNode.getDescription()); - Assert.assertEquals(expectedNode.getInvariantUuid(), actualNode.getInvariantUuid()); - Assert.assertEquals(expectedNode.getUuid(), actualNode.getUuid()); - Assert.assertEquals(expectedNode.getVersion(), actualNode.getVersion()); - } - - private void compareProperties(Map<String, String> expectedProperties, Map<String, String> actualProperties) { - for (Map.Entry<String, String> property : expectedProperties.entrySet()) { - String expectedValue = property.getValue(); - String key = property.getKey(); - String actualValue = actualProperties.get(key); - Assert.assertEquals(expectedValue, actualValue); - } - } - - private ToscaParserMockHelper[] getExpectedServiceModel() throws IOException { - ToscaParserMockHelper[] mockHelpers = { - new ToscaParserMockHelper(Constants.vlUuid, Constants.vlFilePath), - new ToscaParserMockHelper(Constants.vfUuid, Constants.vfFilePath), - new ToscaParserMockHelper(Constants.configurationUuid, Constants.configurationFilePath), - }; - for (ToscaParserMockHelper mockHelper : mockHelpers) { - InputStream jsonFile = VidControllerTest.class.getClassLoader().getResourceAsStream(mockHelper.getFilePath()); - String expectedJsonAsString = IOUtils.toString(jsonFile); - NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class); - mockHelper.setNewServiceModel(newServiceModel1); - } - return mockHelpers; - } - - private Path getCsarPath(String uuid) throws AsdcCatalogException { - return asdcClient.getServiceToscaModel(UUID.fromString(uuid)); - } - - private org.onap.vid.asdc.beans.Service getServiceByUuid(String uuid) throws AsdcCatalogException { - return asdcClient.getService(UUID.fromString(uuid)); - } - - public class Constants { - public static final String configurationUuid = "ee6d61be-4841-4f98-8f23-5de9da846ca7"; - public static final String configurationFilePath = "policy-configuration-csar.JSON"; - static final String vfUuid = "48a52540-8772-4368-9cdb-1f124ea5c931"; - static final String vlUuid = "cb49608f-5a24-4789-b0f7-2595473cb997"; - // public static final String PNFUuid = "68101369-6f08-4e99-9a28-fa6327d344f3"; - static final String vfFilePath = "vf-csar.JSON"; - static final String vlFilePath = "vl-csar.JSON"; -// public static final String PNFFilePath = "/Users/Oren/Git/Att/vid_internal/vid-app-common/src/main/resources/pnf.csar"; - - } - -}
\ No newline at end of file +// +// @Test +// public void assertEqualsBetweenVolumeGroups() throws Exception { +// for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { +// Map<String, VolumeGroup> actualVolumeGroups = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVolumeGroups(); +// Map<String, VolumeGroup> expectedVolumeGroups = mockHelper.getNewServiceModel().getVolumeGroups(); +// JsonAssert.assertJsonEquals(actualVolumeGroups, expectedVolumeGroups); +// } +// } +// +// @Test +// public void assertEqualsBetweenVfModules() throws Exception { +// for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { +// Map<String, VfModule> actualVfModules = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVfModules(); +// Map<String, VfModule> expectedVfModules = mockHelper.getNewServiceModel().getVfModules(); +// //need to uncomment after 1906 merge +// //JsonAssert.assertJsonEquals(actualVfModules, expectedVfModules); +// } +// } +// +// /*@Test +// public void assertEqualsBetweenPolicyConfigurationNodes() throws Exception { +// for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { +// Map<String, PortMirroringConfig> actualConfigurations = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); +// Map<String, PortMirroringConfig> expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); +// JsonAssert.assertJsonEquals(actualConfigurations, expectedConfigurations); +// } +// }*/ +// +// @Test +// public void assertEqualsBetweenServiceProxyNodes() throws Exception { +// for (ToscaParserMockHelper mockHelper : getExpectedServiceModel()) { +// Map<String, ServiceProxy> actualServiceProxies = p2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getServiceProxies(); +// Map<String, ServiceProxy> expectedServiceProxies = mockHelper.getNewServiceModel().getServiceProxies(); +// JsonAssert.assertJsonEquals(actualServiceProxies, expectedServiceProxies); +// } +// } +// +// private void verifyBaseNodeProperties(Node expectedNode, Node actualNode) { +// Assert.assertEquals(expectedNode.getName(), actualNode.getName()); +// Assert.assertEquals(expectedNode.getCustomizationUuid(), actualNode.getCustomizationUuid()); +// Assert.assertEquals(expectedNode.getDescription(), actualNode.getDescription()); +// Assert.assertEquals(expectedNode.getInvariantUuid(), actualNode.getInvariantUuid()); +// Assert.assertEquals(expectedNode.getUuid(), actualNode.getUuid()); +// Assert.assertEquals(expectedNode.getVersion(), actualNode.getVersion()); +// } +// +// private void compareProperties(Map<String, String> expectedProperties, Map<String, String> actualProperties) { +// for (Map.Entry<String, String> property : expectedProperties.entrySet()) { +// String expectedValue = property.getValue(); +// String key = property.getKey(); +// String actualValue = actualProperties.get(key); +// Assert.assertEquals(expectedValue, actualValue); +// } +// } +// +// private ToscaParserMockHelper[] getExpectedServiceModel() throws IOException { +// ToscaParserMockHelper[] mockHelpers = { +// new ToscaParserMockHelper(Constants.vlUuid, Constants.vlFilePath), +// new ToscaParserMockHelper(Constants.vfUuid, Constants.vfFilePath), +// new ToscaParserMockHelper(Constants.configurationUuid, Constants.configurationFilePath), +// }; +// for (ToscaParserMockHelper mockHelper : mockHelpers) { +// InputStream jsonFile = VidControllerTest.class.getClassLoader().getResourceAsStream(mockHelper.getFilePath()); +// String expectedJsonAsString = IOUtils.toString(jsonFile); +// NewServiceModel newServiceModel1 = om.readValue(expectedJsonAsString, NewServiceModel.class); +// mockHelper.setNewServiceModel(newServiceModel1); +// } +// return mockHelpers; +// } +// +// private Path getCsarPath(String uuid) throws AsdcCatalogException { +// return asdcClient.getServiceToscaModel(UUID.fromString(uuid)); +// } +// +// private org.onap.vid.asdc.beans.Service getServiceByUuid(String uuid) throws AsdcCatalogException { +// return asdcClient.getService(UUID.fromString(uuid)); +// } +// +// public class Constants { +// public static final String configurationUuid = "ee6d61be-4841-4f98-8f23-5de9da846ca7"; +// public static final String configurationFilePath = "policy-configuration-csar.JSON"; +// static final String vfUuid = "48a52540-8772-4368-9cdb-1f124ea5c931"; +// static final String vlUuid = "cb49608f-5a24-4789-b0f7-2595473cb997"; +// // public static final String PNFUuid = "68101369-6f08-4e99-9a28-fa6327d344f3"; +// static final String vfFilePath = "vf-csar.JSON"; +// static final String vlFilePath = "vl-csar.JSON"; +//// public static final String PNFFilePath = "/Users/Oren/Git/Att/vid_internal/vid-app-common/src/main/resources/pnf.csar"; +// +// } +// +//}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java b/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java index 843883cd..e7a7e3a3 100644 --- a/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/dao/FnAppDoaImplTest.java @@ -25,42 +25,42 @@ public class FnAppDoaImplTest { url = null; username = null; password = null; - result = FnAppDoaImpl.getConnection(driver2, url, username, password); + result = FnAppDoaImpl.getConnection(driver2, url, username); Assert.assertEquals(null, result); // test 2 url = ""; username = null; password = null; - result = FnAppDoaImpl.getConnection(driver2, url, username, password); + result = FnAppDoaImpl.getConnection(driver2, url, username); Assert.assertEquals(null, result); // test 3 username = null; url = null; password = null; - result = FnAppDoaImpl.getConnection(driver2, url, username, password); + result = FnAppDoaImpl.getConnection(driver2, url, username); Assert.assertEquals(null, result); // test 4 username = ""; url = null; password = null; - result = FnAppDoaImpl.getConnection(driver2, url, username, password); + result = FnAppDoaImpl.getConnection(driver2, url, username); Assert.assertEquals(null, result); // test 5 password = null; url = null; username = null; - result = FnAppDoaImpl.getConnection(driver2, url, username, password); + result = FnAppDoaImpl.getConnection(driver2, url, username); Assert.assertEquals(null, result); // test 6 password = ""; url = null; username = null; - result = FnAppDoaImpl.getConnection(driver2, url, username, password); + result = FnAppDoaImpl.getConnection(driver2, url, username); Assert.assertEquals(null, result); } diff --git a/vid-app-common/src/test/java/org/onap/vid/integrationTest/AaiIntegrationTest.java b/vid-app-common/src/test/java/org/onap/vid/integrationTest/AaiIntegrationTest.java index a7c5a275..e35472ad 100644 --- a/vid-app-common/src/test/java/org/onap/vid/integrationTest/AaiIntegrationTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/integrationTest/AaiIntegrationTest.java @@ -1,13 +1,11 @@ package org.onap.vid.integrationTest; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.aai.AaiClient; import org.onap.vid.aai.AaiClientInterface; import org.onap.vid.aai.AaiResponse; import org.onap.vid.aai.model.GetServiceModelsByDistributionStatusResponse; import org.onap.vid.aai.model.Result; +import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.springframework.test.context.web.WebAppConfiguration; @@ -23,12 +21,10 @@ public class AaiIntegrationTest extends AbstractTestNGSpringContextTests { @Autowired - MockServletContext servletContext; - + AaiClientInterface aaiClient; - @Test - public void testGetServiceModelsFromAai() throws Exception { - AaiClientInterface aaiClient = new AaiClient(servletContext); + @Test(enabled = false) + public void testGetServiceModelsFromAai() { AaiResponse<GetServiceModelsByDistributionStatusResponse> serviceModelsByDistributionStatusResponse = aaiClient.getServiceModelsByDistributionStatus(); GetServiceModelsByDistributionStatusResponse response = serviceModelsByDistributionStatusResponse.getT(); for(Result result: response.getResults()){ @@ -38,6 +34,4 @@ public class AaiIntegrationTest extends AbstractTestNGSpringContextTests { Assert.assertNotNull(result.getModel().getModelVers().getModelVer().get(0).getModelVersion()); } } - - } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java new file mode 100644 index 00000000..b51553be --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java @@ -0,0 +1,68 @@ +package org.onap.vid.job.command; + +import com.google.common.collect.ImmutableMap; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobCommand; +import org.onap.vid.job.JobType; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class JobCommandFactoryTest { + + private JobCommandFactory jobCommandFactory; + + @Mock + private Job job; + + @Mock + private JobCommand mockCommand; + + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @BeforeMethod + public void setUp() { + jobCommandFactory = new JobCommandFactory(any -> mockCommand); + } + + @DataProvider + public Object[][] jobTypes() { + return Arrays.stream( + JobType.values() + ).map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{}); + + } + + @Test(dataProvider = "jobTypes") + public void givenJob_createCommandCallsTheInitAndReturnsTheInstance(JobType jobType) { + + final UUID uuid = UUID.randomUUID(); + final Map<String, Object> data = ImmutableMap.of("foo", "bar"); + + when(job.getType()).thenReturn(jobType); + when(job.getUuid()).thenReturn(uuid); + when(job.getData()).thenReturn(data); + + final JobCommand command = jobCommandFactory.toCommand(job); + + verify(mockCommand).init(uuid, data); + + assertThat(command, equalTo(mockCommand)); + } + +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java new file mode 100644 index 00000000..b7e8e35a --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java @@ -0,0 +1,101 @@ +package org.onap.vid.job.impl; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.RandomUtils; +import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; +import org.hamcrest.Matcher; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.*; +import org.onap.vid.job.command.HttpCallCommand; +import org.onap.vid.job.command.JobCommandFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Map; +import java.util.UUID; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class JobWorkerTest { + + @InjectMocks + private JobWorker jobWorker = new JobWorker(); + + @Mock + private JobCommandFactory jobCommandFactory; + + private final JobCommand jobCommand = mock(JobCommand.class); + private Job jobUnderTest; + private JobAdapter.AsyncJobRequest originalData; + private JobType originalType; + + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); + + when(jobCommandFactory.toCommand(any())).thenReturn(jobCommand); + + originalData = new JobAdapter.AsyncJobRequest() { + public final Map datum = ImmutableMap.of("some", "data"); + public final String foobar = "aux"; + }; + + originalType = JobType.ServiceInstantiation; + jobUnderTest = new JobAdapterImpl().createJob( + originalType, + originalData, + UUID.randomUUID(), + "my user id", + RandomUtils.nextInt() + ); + } + + @Test + public void executeJobAndStepToNext_givenNull_onlyStatusModified() { + + assertNextJobAfterExecuteJob(null, new String[]{"status"}, allOf( + hasProperty("status", is(Job.JobStatus.STOPPED)), + hasProperty("data", hasEntry("request", originalData)), + hasProperty("type", is(originalType))) + ); + } + + @Test + public void executeJobAndStepToNext_givenNextJob_jobDataIsModified() { + + final Job.JobStatus nextStatus = Job.JobStatus.IN_PROGRESS; + + final UUID jobUuid = UUID.randomUUID(); + final NextCommand nextCommand = new NextCommand(nextStatus, new HttpCallCommand("my strange url", jobUuid)); + + String[] excludedFields = {"status", "data", "type"}; + + assertNextJobAfterExecuteJob(nextCommand, excludedFields, allOf( + hasProperty("status", is(nextStatus)), + hasProperty("data", is(nextCommand.getCommand().getData())), + hasProperty("type", is(nextCommand.getCommand().getType()))) + ); + } + + private void assertNextJobAfterExecuteJob(NextCommand nextCommand, String[] excludedFields, Matcher<Job> jobMatcher) { + when(jobCommand.call()).thenReturn(nextCommand); + + String jobBefore = new ReflectionToStringBuilder(jobUnderTest, ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames(excludedFields).toString(); + + ////// FUNCTION UNDER TEST ///// + Job nextJob = jobWorker.executeJobAndGetNext(jobUnderTest); + //////////////////////////////// + + String jobAfter = new ReflectionToStringBuilder(nextJob, ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames(excludedFields).toString(); + + assertThat(nextJob, jobMatcher); + assertThat(jobAfter, equalTo(jobBefore)); + } +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java new file mode 100644 index 00000000..36f4bdd4 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java @@ -0,0 +1,153 @@ +package org.onap.vid.mso; + +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.mso.rest.RequestDetails; +import org.onap.vid.properties.Features; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +import org.springframework.test.context.web.WebAppConfiguration; +import org.testng.Assert; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.vid.controllers.MsoController.SVC_INSTANCE_ID; +import static org.onap.vid.controllers.MsoController.VNF_INSTANCE_ID; +import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath; + +@ContextConfiguration(classes = {SystemProperties.class}) +@WebAppConfiguration +public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { + + @InjectMocks + private MsoBusinessLogicImpl msoBusinessLogic; + + @Mock + private FeatureManager featureManagerMock; + + @Mock + private MsoInterface msoInterfaceMock; + + + @BeforeTest + public void initMocks(){ + MockitoAnnotations.initMocks(this); + } + + @Test + public void validateEndpointPath_endPointIsNotEmptyAndVaild_returnProperty(){ + System.setProperty("TestEnv","123"); + String foundEndPoint = validateEndpointPath("TestEnv"); + Assert.assertEquals("123",foundEndPoint); + } + + @Test(expectedExceptions = RuntimeException.class) + public void validateEndpointPath_endPointIsNull_throwRuntimeException(){ + validateEndpointPath("NotExists"); + } + + @Test(expectedExceptions = RuntimeException.class) + public void validateEndpointPath_endPointIsNotEmptyButDoesntExists_throwRuntimeException(){ + System.setProperty("EmptyEndPoint",""); + validateEndpointPath("EmptyEndPoint"); + } + + + //@Test(dataProvider = "unAssignOrDeleteParams") + public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOffOrUnAssignFlagIsFalse(boolean isAssignFlag,String status) { + Mockito.reset(msoInterfaceMock); + String endpoint = validateEndpointPath(isAssignFlag ? MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE : MsoProperties.MSO_REST_API_SVC_INSTANCE); + RequestDetails requestDetails = new RequestDetails(); + + when(featureManagerMock.isActive(Features.FLAG_UNASSIGN_SERVICE)).thenReturn(isAssignFlag); + + msoBusinessLogic.deleteSvcInstance(requestDetails, "tempId", status); + + verify(msoInterfaceMock).deleteSvcInstance(requestDetails, endpoint + "/tempId"); + } + + @DataProvider + public Object[][] unAssignOrDeleteParams() { + return new Object[][]{ + {Boolean.FALSE, "active"}, + {Boolean.FALSE, "created"}, + {Boolean.TRUE, "Active"}, + {Boolean.TRUE, "unexpected-status"}, + }; + } + + //@Test(dataProvider = "unAssignStatus") + public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOnAndUnAssignFlagIsTrue(String status) { + Mockito.reset(msoInterfaceMock); + // in the test Features.FLAG_UNASSIGN_SERVICE is active so the endpoint should be MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE + String endpoint = validateEndpointPath(MsoProperties.MSO_DELETE_OR_UNASSIGN_REST_API_SVC_INSTANCE); + RequestDetails requestDetails = new RequestDetails(); + + when(featureManagerMock.isActive(Features.FLAG_UNASSIGN_SERVICE)).thenReturn(true); + + msoBusinessLogic.deleteSvcInstance(requestDetails, "tempId", status); + + verify(msoInterfaceMock).unassignSvcInstance(requestDetails, endpoint + "/tempId/unassign"); + } + + @DataProvider + public Object[][] unAssignStatus() { + return new Object[][]{ + {"Created"}, + {"Pendingdelete"}, + {"pending-Delete"}, + {"Assigned"} + }; + } + + @Test + public void deleteVnf_verifyEndPointPathConstructing() { + String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE); + RequestDetails requestDetails = new RequestDetails(); + + String vnf_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, "serviceInstanceTempId"); + + msoBusinessLogic.deleteVnf(requestDetails, "serviceInstanceTempId","vnfInstanceTempId"); + verify(msoInterfaceMock).deleteVnf(requestDetails, vnf_endpoint + "/vnfInstanceTempId"); + } + + @Test + public void deleteVfModule_verifyEndPointPathConstructing() { + String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + RequestDetails requestDetails = new RequestDetails(); + + String vf__modules_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, "serviceInstanceTempId").replaceFirst(VNF_INSTANCE_ID, "vnfInstanceTempId"); + + msoBusinessLogic.deleteVfModule(requestDetails, "serviceInstanceTempId","vnfInstanceTempId", "vfModuleTempId"); + verify(msoInterfaceMock).deleteVfModule(requestDetails, vf__modules_endpoint + "/vfModuleTempId" ); + } + + @Test + public void insertServiceInstantiationToDB_StartJob() { + +// broker = new JobsBrokerServiceInDatabaseImpl(dataAccessServiceMock, sessionFactory); +// ((JobsBrokerServiceInDatabaseImpl)broker).deleteAll(); +// +//// msoBusinessLogic.setDataAccessService(dataAccessServiceMock); +//// msoBusinessLogic.setJobsBrokerService(broker); +//// msoBusinessLogic.setJobAdapter(jobAdapter); +// +// ServiceInstantiation serviceInstantiation = new ServiceInstantiation(); +// serviceInstantiation.setCount(2); +// serviceInstantiation.setInstanceName("TestName"); +// +// msoBusinessLogic.pushBulkJob(serviceInstantiation, "testUserId"); +// +// List<ServiceInfo> serviceInfoList = dataAccessServiceMock.getList(ServiceInfo.class, null); +// int k = 9; +// Assert.assertEquals(serviceInstantiation, containsInAnyOrder(serviceInfoList.toArray())); + } +} + diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java index 69bcabaa..738e8df0 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java @@ -5,15 +5,11 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.controllers.MsoConfig; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.rest.RequestDetails; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.web.WebAppConfiguration; +import org.onap.vid.mso.rest.RequestDetailsWrapper; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @@ -23,9 +19,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @Test -@ContextConfiguration(classes = { SystemProperties.class, MsoConfig.class }) -@WebAppConfiguration -public class MsoBusinessLogicTest extends AbstractTestNGSpringContextTests { +public class MsoBusinessLogicTest { @InjectMocks private MsoBusinessLogicImpl msoBusinessLogic; @@ -41,9 +35,10 @@ public class MsoBusinessLogicTest extends AbstractTestNGSpringContextTests { @Test public void testCreateInstance() throws Exception { String instanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; - final RequestDetails requestDetails = setRequestDetails("mso_request_create_configuration.json"); - Mockito.doReturn(getOkResponse(instanceId)).when(msoClient).createConfigurationInstance(requestDetails, "/serviceInstances/v6/3f93c7cb-2fd0-4557-9514-e189b7b04f9d/configurations"); - final MsoResponseWrapper msoResponseWrapper = msoBusinessLogic.createConfigurationInstance(requestDetails, instanceId); + final RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); + requestDetailsWrapper.requestDetails = setRequestDetails("mso_request_create_configuration.json"); + Mockito.doReturn(getOkResponse(instanceId)).when(msoClient).createConfigurationInstance(requestDetailsWrapper, "/serviceInstances/v6/3f93c7cb-2fd0-4557-9514-e189b7b04f9d/configurations"); + final MsoResponseWrapper msoResponseWrapper = msoBusinessLogic.createConfigurationInstance(requestDetailsWrapper, instanceId); assertNotNull(msoResponseWrapper); assertEquals(202, msoResponseWrapper.getStatus()); diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java index 633f95c5..5c5d6fd4 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java @@ -6,27 +6,20 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import org.apache.commons.io.IOUtils; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.controllers.MsoConfig; import org.onap.vid.controllers.OperationalEnvironmentController; -import org.onap.vid.controllers.WebConfig; -import org.onap.vid.controllers.OperationalEnvironmentController.*; +import org.onap.vid.controllers.OperationalEnvironmentController.OperationalEnvironmentManifest; import org.onap.vid.mso.MsoBusinessLogic; +import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; import org.onap.vid.mso.rest.RequestDetails; -import org.onap.vid.properties.AsdcClientConfiguration; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.springframework.test.context.web.WebAppConfiguration; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import javax.inject.Inject; import java.io.IOException; import java.net.URL; import java.util.HashMap; @@ -36,12 +29,9 @@ import java.util.Map; import java.util.stream.Collectors; @Test -@ContextConfiguration(classes = { WebConfig.class, AsdcClientConfiguration.class, SystemProperties.class, MsoConfig.class }) -@WebAppConfiguration -public class MsoOperationalEnvironmentTest extends AbstractTestNGSpringContextTests { +public class MsoOperationalEnvironmentTest { - @Inject - private MsoBusinessLogic msoBusinessLogic; + private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(null,null); @Test(dataProvider = "getOperationalEnvironmentActivationPermutations") public void testJsonResultOfOperationalEnvironmentActivationRequestDetails(HashMap<String, String> permutation) throws IOException { @@ -63,7 +53,7 @@ public class MsoOperationalEnvironmentTest extends AbstractTestNGSpringContextTe } @DataProvider - private Object[][] getOperationalEnvironmentActivationPermutations() throws IOException { + private Object[][] getOperationalEnvironmentActivationPermutations() { final String manifest = "" + "{" + " \"serviceModelList\": [" + @@ -106,7 +96,7 @@ public class MsoOperationalEnvironmentTest extends AbstractTestNGSpringContextTe } @DataProvider - private Object[][] getOperationalEnvironmentCreationPermutations() throws IOException { + private Object[][] getOperationalEnvironmentCreationPermutations() { final ImmutableListMultimap<String, String> options = ImmutableListMultimap.<String, String>builder() // instanceName, ecompInstanceId, ecompInstanceName, operationalEnvType, tenantContext, workloadContext @@ -137,7 +127,7 @@ public class MsoOperationalEnvironmentTest extends AbstractTestNGSpringContextTe } @DataProvider - private Object[][] getOperationalEnvironmentDeactivationPermutations() throws IOException { + private Object[][] getOperationalEnvironmentDeactivationPermutations() { final ImmutableListMultimap<String, String> options = ImmutableListMultimap.<String, String>builder() .putAll("<userId>", "instanceName", "Slavica Hadrien") @@ -173,7 +163,7 @@ public class MsoOperationalEnvironmentTest extends AbstractTestNGSpringContextTe return res; } - private void assertThatExpectationIsLikeObject(String expected, Object requestDetails) throws JsonProcessingException { + public static void assertThatExpectationIsLikeObject(String expected, Object requestDetails) throws JsonProcessingException { final String requestDetailsAsString = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(requestDetails); // assert for exact match @@ -197,8 +187,6 @@ public class MsoOperationalEnvironmentTest extends AbstractTestNGSpringContextTe return expected; } - - private OperationalEnvironmentActivateInfo createOperationalEnvironmentActivateInfo(String operationalEnvId, String userId, OperationalEnvironmentManifest manifest, String relatedInstanceId, String relatedInstanceName, String workloadContext) { OperationalEnvironmentController.OperationalEnvironmentActivateBody body = new OperationalEnvironmentController.OperationalEnvironmentActivateBody(relatedInstanceId, relatedInstanceName, workloadContext, manifest); return new OperationalEnvironmentActivateInfo(body, userId, operationalEnvId); @@ -211,5 +199,4 @@ public class MsoOperationalEnvironmentTest extends AbstractTestNGSpringContextTe private OperationalEnvironmentController.OperationalEnvironmentCreateBody createOperationalEnvironmentCreateBody(String instanceName, String ecompInstanceId, String ecompInstanceName, String operationalEnvType, String tenantContext, String workloadContext) { return new OperationalEnvironmentController.OperationalEnvironmentCreateBody(instanceName, ecompInstanceId, ecompInstanceName, operationalEnvType, tenantContext, workloadContext); } - } diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java index ba939580..400a34e9 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/AsyncRequestStatusTest.java @@ -13,50 +13,6 @@ public class AsyncRequestStatusTest { @Test - public void testGetInstanceIds() throws Exception { - AsyncRequestStatus testSubject; - InstanceIds result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getInstanceIds(); - } - - - @Test - public void testSetInstanceIds() throws Exception { - AsyncRequestStatus testSubject; - InstanceIds instanceIds = null; - - // default test - testSubject = createTestSubject(); - testSubject.setInstanceIds(instanceIds); - } - - - @Test - public void testGetRequestStatus() throws Exception { - AsyncRequestStatus testSubject; - RequestStatus result; - - // default test - testSubject = createTestSubject(); - result = testSubject.getRequestStatus(); - } - - - @Test - public void testSetRequestStatus() throws Exception { - AsyncRequestStatus testSubject; - RequestStatus requestStatus = null; - - // default test - testSubject = createTestSubject(); - testSubject.setRequestStatus(requestStatus); - } - - - @Test public void testToString() throws Exception { AsyncRequestStatus testSubject; String result; diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java index 01d1e9b5..59c2c704 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java @@ -1,7 +1,6 @@ package org.onap.vid.mso.rest; import org.junit.Test; -import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapperInterface; import org.onap.vid.mso.RestObject; @@ -90,7 +89,7 @@ public class MsoRestClientNewTest { @Test public void testCreateConfigurationInstance() throws Exception { MsoRestClientNew testSubject; - RequestDetails requestDetails = null; + RequestDetailsWrapper requestDetails = null; String endpoint = ""; MsoResponseWrapper result; @@ -294,7 +293,7 @@ public class MsoRestClientNewTest { @Test public void testDeleteConfiguration() throws Exception { MsoRestClientNew testSubject; - RequestDetails requestDetails = null; + RequestDetailsWrapper requestDetails = null; String pmc_endpoint = ""; MsoResponseWrapper result; @@ -339,7 +338,7 @@ public class MsoRestClientNewTest { @Test public void testChangeManagementUpdate() throws Exception { MsoRestClientNew testSubject; - RequestDetailsWrapper requestDetails = null; + org.onap.vid.changeManagement.RequestDetailsWrapper requestDetails = null; String endpoint = ""; MsoResponseWrapperInterface result; diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java index e0ba5593..0cfc0be1 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java @@ -1,78 +1,74 @@ -//package org.onap.vid.mso.rest; -// -//import com.fasterxml.jackson.databind.ObjectMapper; -//import org.json.JSONObject; -//import org.junit.Assert; -//import org.onap.portalsdk.core.util.SystemProperties; -//import org.onap.vid.changeManagement.RequestDetails; -//import org.onap.vid.controller.LocalWebConfig; -//import org.onap.vid.domain.mso.CloudConfiguration; -//import org.onap.vid.domain.mso.ModelInfo; -//import org.onap.vid.domain.mso.RequestInfo; -//import org.onap.vid.domain.mso.RequestParameters; -//import org.onap.vid.mso.MsoBusinessLogic; -//import org.onap.vid.mso.MsoBusinessLogicImpl; -//import org.onap.vid.mso.rest.MsoRestClientNew; -//import org.springframework.test.context.ContextConfiguration; -//import org.springframework.test.context.web.WebAppConfiguration; -//import org.testng.annotations.Test; -// -// -//@ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) -//@WebAppConfiguration -//public class MsoRestClientTest { -// -// -// private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(new MsoRestClientNew()); -// private ObjectMapper om = new ObjectMapper(); -// -// @Test -// public void createInPlaceMsoRequest() { -// String result = null; -// try { -// RequestDetails requestDetails = generateMockMsoRequest(); -// result = om.writeValueAsString(msoBusinessLogic.generateInPlaceMsoRequest(requestDetails)); -// -// } catch (Exception e) { -// e.printStackTrace(); -// -// } -// if (result == null) { -// Assert.fail("Failed to create mso request"); -// } -// JSONObject jsonObj = new JSONObject(result); -// Assert.assertNotNull(jsonObj.getJSONObject("requestDetails")); -// -// -// } -// -// private RequestDetails generateMockMsoRequest() { -// RequestDetails requestDetails = new RequestDetails(); -// requestDetails.setVnfInstanceId("vnf-instance-id"); -// requestDetails.setVnfName("vnf-name"); -// CloudConfiguration cloudConfiguration = new CloudConfiguration(); -// cloudConfiguration.setTenantId("tenant-id"); -// cloudConfiguration.setLcpCloudRegionId("lcp-region"); -// requestDetails.setCloudConfiguration(cloudConfiguration); -// ModelInfo modelInfo = new ModelInfo(); -// modelInfo.setModelInvariantId("model-invarient-id"); -// modelInfo.setModelCustomizationName("modelCustomizationName"); -// requestDetails.setModelInfo(modelInfo); -// RequestInfo requestInfo = new RequestInfo(); -// requestInfo.setRequestorId("ok883e"); -// requestInfo.setSource("VID"); -// requestDetails.setRequestInfo(requestInfo); -// RequestParameters requestParameters = new RequestParameters(); -// requestParameters.setSubscriptionServiceType("subscriber-service-type"); -// requestParameters.setAdditionalProperty("a", 1); -// requestParameters.setAdditionalProperty("b", 2); -// requestParameters.setAdditionalProperty("c", 3); -// requestParameters.setAdditionalProperty("d", 4); -// String payload = "{\"existing-software-version\": \"3.1\",\"new-software-version\": \"3.2\", \"operations-timeout\": \"3600\"}"; -// requestParameters.setAdditionalProperty("payload", payload); -// -// requestDetails.setRequestParameters(requestParameters); -// return requestDetails; -// } -// -//} +package org.onap.vid.mso.rest; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.json.JSONObject; +import org.junit.Assert; +import org.onap.vid.changeManagement.RequestDetails; +import org.onap.vid.domain.mso.CloudConfiguration; +import org.onap.vid.domain.mso.ModelInfo; +import org.onap.vid.domain.mso.RequestInfo; +import org.onap.vid.domain.mso.RequestParameters; +import org.onap.vid.mso.MsoBusinessLogic; +import org.onap.vid.mso.MsoBusinessLogicImpl; +import org.onap.vid.mso.rest.MsoRestClientNew; +import org.onap.vid.controllers.LocalWebConfig; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.web.WebAppConfiguration; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + + +@ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) +@WebAppConfiguration +public class MsoRestClientTest { + + + private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(new MsoRestClientNew(), null); + private ObjectMapper om = new ObjectMapper(); + + @Test + public void createInPlaceMsoRequest() { + String result = null; + try { + RequestDetails requestDetails = generateMockMsoRequest(); + result = om.writeValueAsString(msoBusinessLogic.generateInPlaceMsoRequest(requestDetails)); + } catch (Exception e) { + e.printStackTrace(); + } + if (result == null) { + Assert.fail("Failed to create mso request"); + } + JSONObject jsonObj = new JSONObject(result); + Assert.assertNotNull(jsonObj.getJSONObject("requestDetails")); + } + + private RequestDetails generateMockMsoRequest() { + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setVnfInstanceId("vnf-instance-id"); + requestDetails.setVnfName("vnf-name"); + CloudConfiguration cloudConfiguration = new CloudConfiguration(); + cloudConfiguration.setTenantId("tenant-id"); + cloudConfiguration.setLcpCloudRegionId("lcp-region"); + requestDetails.setCloudConfiguration(cloudConfiguration); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelInvariantId("model-invarient-id"); + modelInfo.setModelCustomizationName("modelCustomizationName"); + requestDetails.setModelInfo(modelInfo); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setRequestorId("ok883e"); + requestInfo.setSource("VID"); + requestDetails.setRequestInfo(requestInfo); + RequestParameters requestParameters = new RequestParameters(); + requestParameters.setSubscriptionServiceType("subscriber-service-type"); + requestParameters.setAdditionalProperty("a", 1); + requestParameters.setAdditionalProperty("b", 2); + requestParameters.setAdditionalProperty("c", 3); + requestParameters.setAdditionalProperty("d", 4); + String payload = "{\"existing_software_version\": \"3.1\",\"new_software_version\": \"3.2\", \"operations_timeout\": \"3600\"}"; + requestParameters.setAdditionalProperty("payload", payload); + + requestDetails.setRequestParameters(requestParameters); + return requestDetails; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestId.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java index 51071a85..da2600ea 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestId.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java @@ -1,17 +1,15 @@ package org.onap.vid.mso.rest; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.reflect.FieldUtils; import org.mockito.*; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.onap.vid.aai.util.AAIRestInterface; import org.onap.vid.asdc.rest.RestfulAsdcClient; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; +import org.onap.vid.testUtils.TestUtils; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -23,14 +21,7 @@ import org.testng.annotations.Test; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.client.Client; import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.io.Serializable; -import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; @@ -39,11 +30,10 @@ import java.util.stream.Stream; import static java.util.UUID.randomUUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; -public class OutgoingRequestId { +public class OutgoingRequestIdTest { @InjectMocks @@ -70,24 +60,14 @@ public class OutgoingRequestId { @DataProvider public Object[][] sdcMethods() { return Stream.<ThrowingConsumer<RestfulAsdcClient>>of( - - client -> client.getResource(randomUUID()), - client -> client.getResourceArtifact(randomUUID(), randomUUID()), - RestfulAsdcClient::getResources, - client -> client.getResources(ImmutableMap.of()), - client -> client.getResourceToscaModel(randomUUID()), client -> client.getService(randomUUID()), - client -> client.getServiceArtifact(randomUUID(), randomUUID()), - RestfulAsdcClient::getServices, - client -> client.getServices(ImmutableMap.of()), client -> client.getServiceToscaModel(randomUUID()) - ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); } @Test(dataProvider = "sdcMethods") public void sdc(Consumer<RestfulAsdcClient> f) throws Exception { - final Mocks mocks = setAndGetMocksInsideRestImpl(restfulAsdcClient); + final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restfulAsdcClient); f.accept(restfulAsdcClient); @@ -109,7 +89,7 @@ public class OutgoingRequestId { @Test(dataProvider = "msoMethods") public void mso(Consumer<RestMsoImplementation> f) throws Exception { - final Mocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation.getClass()); + final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); f.accept(restMsoImplementation); @@ -122,15 +102,15 @@ public class OutgoingRequestId { client -> client.RestGet("from app id", "some transId", "/any path", false), client -> client.Delete("whatever source id", "some transId", "/any path"), - client -> client.RestPost("from app id", "some transId", "/any path", "some payload", false), - client -> client.RestPut("from app id", "some transId", "/any path", "some payload", false) + client -> client.RestPost("from app id", "/any path", "some payload", false), + client -> client.RestPut("from app id", "/any path", "some payload", false) ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); } - @Test(dataProvider = "aaiMethods") + //@Test(dataProvider = "aaiMethods") public void aai(Consumer<AAIRestInterface> f) throws Exception { - final Mocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface.getClass()); + final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface); f.accept(aaiRestInterface); @@ -187,8 +167,8 @@ public class OutgoingRequestId { .orElse(key); } - private Mocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException { - Mocks mocks = new Mocks(); + private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException { + TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); Client fakeClient = mocks.getFakeClient(); FieldUtils.writeStaticField(clazz, "client", fakeClient, true); @@ -196,8 +176,8 @@ public class OutgoingRequestId { return mocks; } - private Mocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException { - Mocks mocks = new Mocks(); + private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException { + TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); Client fakeClient = mocks.getFakeClient(); FieldUtils.writeField(instance, "client", fakeClient, true); @@ -205,41 +185,6 @@ public class OutgoingRequestId { return mocks; } - private static class Mocks { - private final Client fakeClient; - private final Invocation.Builder fakeBuilder; - - Client getFakeClient() { - return fakeClient; - } - - Invocation.Builder getFakeBuilder() { - return fakeBuilder; - } - - Mocks() { - final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType()); - - fakeClient = mock(Client.class, mockSettings); - fakeBuilder = mock(Invocation.Builder.class, mockSettings); - final WebTarget fakeWebTarget = mock(WebTarget.class, mockSettings); - final Response fakeResponse = mock(Response.class, mockSettings); - - TriesToReturnMockByType.setAvailableMocks( - fakeClient, - fakeWebTarget, - fakeBuilder, - fakeResponse - ); - - Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null); - Mockito.when(fakeBuilder.get(eq(InputStream.class))).thenReturn(new ByteArrayInputStream(new byte[]{})); - Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null); - - Mockito.when(fakeResponse.getStatus()).thenReturn(200); - } - } - @FunctionalInterface public interface ThrowingConsumer<T> extends Consumer<T> { @Override @@ -254,27 +199,4 @@ public class OutgoingRequestId { void acceptThrows(T t) throws Exception; } - /* - inspired out from newer Mockito version - returns a mock from given list if it's a matching return-type - */ - public static class TriesToReturnMockByType implements Answer<Object>, Serializable { - private final Answer<Object> defaultReturn = RETURNS_DEFAULTS; - private static List<Object> availableMocks = ImmutableList.of(); - - static void setAvailableMocks(Object... mocks) { - availableMocks = ImmutableList.copyOf(mocks); - } - - public Object answer(InvocationOnMock invocation) throws Throwable { - Class<?> methodReturnType = invocation.getMethod().getReturnType(); - - return availableMocks.stream() - .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass())) - //.peek(m -> System.out.println("found a mock: " + m.getClass().getName())) - .findFirst() - .orElse(defaultReturn.answer(invocation)); - } - } - } diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java index 153e1656..e4716d58 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java @@ -61,7 +61,7 @@ public class RequestDetailsTest { @Test public void testGetRelatedInstanceList() throws Exception { RequestDetails testSubject; - List<RelatedModel> result; + List<RelatedInstanceWrapper> result; // default test testSubject = createTestSubject(); @@ -72,7 +72,7 @@ public class RequestDetailsTest { @Test public void testSetRelatedInstanceList() throws Exception { RequestDetails testSubject; - List<RelatedModel> relatedInstanceList = null; + List<RelatedInstanceWrapper> relatedInstanceList = null; // default test testSubject = createTestSubject(); diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceFactoryTest.java deleted file mode 100644 index 08cdd5f1..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceFactoryTest.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.onap.vid.scheduler; - -import org.junit.Test; - -public class SchedulerRestInterfaceFactoryTest { - - private SchedulerRestInterfaceFactory createTestSubject() { - return new SchedulerRestInterfaceFactory(); - } - - @Test - public void testGetInstance() throws Exception { - SchedulerRestInterfaceIfc result; - - // default test - result = SchedulerRestInterfaceFactory.getInstance(); - } -}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java deleted file mode 100644 index 5f861dfe..00000000 --- a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.onap.vid.scheduler; - -import org.apache.poi.hssf.record.formula.functions.T; -import org.json.simple.JSONObject; -import org.junit.Test; - -public class SchedulerRestInterfaceTest { - - private SchedulerRestInterface createTestSubject() { - return new SchedulerRestInterface(); - } - - - - @Test - public void testLogRequest() throws Exception { - SchedulerRestInterface testSubject; - JSONObject requestDetails = null; - - // default test - testSubject = createTestSubject(); - testSubject.logRequest(requestDetails); - } - - -}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java new file mode 100644 index 00000000..04890e33 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/AaiResponseTranslatorTest.java @@ -0,0 +1,132 @@ +package org.onap.vid.services; + +import org.codehaus.jackson.JsonNode; +import org.codehaus.jackson.map.ObjectMapper; +import org.onap.vid.aai.AaiResponseTranslator; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataError; +import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigDataOk; +import org.testng.annotations.Test; + +import java.io.IOException; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; + +@Test +public class AaiResponseTranslatorTest { + + private static final ObjectMapper objectMapper = new ObjectMapper(); + + @Test + public void extractPortMirroringConfigData_givenValidAaiResponse_yieldCloudRegionId() throws IOException { + + final JsonNode aaiPayload = objectMapper.readTree("" + + "{" + + " \"results\": [{" + + " \"id\": \"2979590232\"," + + " \"node-type\": \"cloud-region\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/SDNO-S-BcloudReg-E1802\"," + + " \"properties\": {" + + " \"cloud-owner\": \"att-aic\"," + + " \"cloud-region-id\": \"THE-EXPECTED-REGION-ID\"," + + " \"sriov-automation\": false," + + " \"resource-version\": \"1513631040564\"" + + " }" + + " }," + + " {" + + " \"id\": \"2979598424\"," + + " \"node-type\": \"generic-vnf\"," + + " \"url\": \"/aai/v12/network/generic-vnfs/generic-vnf/SOURCE-gVnf-E1802\"," + + " \"properties\": {" + + " \"vnf-id\": \"SOURCE-gVnf-E1802\"," + + " \"vnf-name\": \"SOURCE-vnf-SDNO\"," + + " \"vnf-type\": \"S-1-SDNO\"," + + " \"service-id\": \"a9a77d5a-123e-4-SDNO\"," + + " \"orchestration-status\": \"active\"," + + " \"in-maint\": true," + + " \"is-closed-loop-disabled\": false," + + " \"resource-version\": \"1513631043149\"" + + " }" + + " }" + + " ]" + + "}"); + + PortMirroringConfigData portMirroringConfigData = + new AaiResponseTranslator().extractPortMirroringConfigData(aaiPayload); + + assertThat(portMirroringConfigData, is(instanceOf(PortMirroringConfigDataOk.class))); + assertThat(((PortMirroringConfigDataOk) portMirroringConfigData).getCloudRegionId(), is("THE-EXPECTED-REGION-ID")); + + } + + @Test + public void extractPortMirroringConfigData_givenKindOfValidAaiResponse_yieldCloudRegionId() throws IOException { + // some completley different response, but with + // the results[cloud-region]->properties->cloud-region-id + + final JsonNode aaiPayload = objectMapper.readTree("" + + "{ " + + " \"results\": [{ " + + " \"node-type\": \"generic-vnf\", " + + " \"url\": \"configuration entries) so that git\" " + + " }, " + + " {}, " + + " { " + + " \"node-type\": \"cloud-region\", " + + " \"but it will not switch\": \"tip commits are reachable\", " + + " \"named\": [{ " + + " \"resource-version\": \"1513631040564\" " + + " }], " + + " \"properties\": { " + + " \"cloud-region-id\": \"THE-EXPECTED-REGION-ID\", " + + " \"oldbranch> will be renamed\": false " + + " } " + + " }, " + + " { " + + " \"node-type\": [\"generic-vnf\", \"can be overridden by using\"] " + + " } " + + " ] " + + "}"); + + PortMirroringConfigData portMirroringConfigData = + new AaiResponseTranslator().extractPortMirroringConfigData(aaiPayload); + + assertThat(portMirroringConfigData, is(instanceOf(PortMirroringConfigDataOk.class))); + assertThat(((PortMirroringConfigDataOk) portMirroringConfigData).getCloudRegionId(), is("THE-EXPECTED-REGION-ID")); + + } + + public void extractPortMirroringConfigData_givenAaiResponseWithoutRegionIdName_yieldException() throws IOException { + + final JsonNode aaiPayload = objectMapper.readTree("" + + "{" + + " \"results\": [{" + + " \"node-type\": \"cloud-region\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/SDNO-S-BcloudReg-E1802\"," + + " \"properties\": {" + + " \"resource-version\": \"1513631040564\"" + + " }" + + " }" + + " ]" + + "}"); + + PortMirroringConfigData portMirroringConfigData = + new AaiResponseTranslator().extractPortMirroringConfigData(aaiPayload); + + assertThat(portMirroringConfigData, is(instanceOf(PortMirroringConfigDataError.class))); + assertThat(((PortMirroringConfigDataError) portMirroringConfigData).getErrorDescription(), + containsString("The node-type 'cloud-region' does not contain the property 'cloud-region-id'")); + assertThat(((PortMirroringConfigDataError) portMirroringConfigData).getRawAaiResponse(), + containsString(aaiPayload.toString()) + ); + + } + + /* + More tests: + [x] cloud-region-id field is missing -- descriptive exception is thrown, including the problematic payload itself + [ ] cloud-region-id field is empty -- descriptive exception etc. + [ ] node-type=="cloud-region" entry is empty -- descriptive exception etc. + */ +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java new file mode 100644 index 00000000..c3d01283 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java @@ -0,0 +1,193 @@ +package org.onap.vid.services; + +import com.google.common.collect.ImmutableMap; +import jersey.repackaged.com.google.common.collect.ImmutableList; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.AaiResponse; +import org.onap.vid.aai.model.AaiNodeQueryResponse; +import org.onap.vid.aai.model.ResourceType; +import org.onap.vid.domain.mso.ModelInfo; +import org.onap.vid.domain.mso.RequestStatus; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.model.serviceInstantiation.VfModule; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AsyncInstantiationBusinessLogicTest; +import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +import org.togglz.core.manager.FeatureManager; + +import javax.inject.Inject; +import java.util.*; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.when; + +public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests { + + public static final String OWNING_ENTITY_ID = "038d99af-0427-42c2-9d15-971b99b9b489"; + public static final String PACKET_CORE = "PACKET CORE"; + public static final String PROJECT_NAME = "{some project name}"; + public static final String SUBSCRIBER_ID = "{some subscriber id}"; + public static final String SUBSCRIBER_NAME = "{some subscriber name}"; + public static final String PRODUCT_FAMILY_ID = "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"; + public static final String INSTANCE_NAME = "vPE_Service"; + public static final String SUBSCRIPTION_SERVICE_TYPE = "VMX"; + public static final String LCP_CLOUD_REGION_ID = "mdt1"; + public static final String A6CA3EE0394ADE9403F075DB23167E = "88a6ca3ee0394ade9403f075db23167e"; + public static final String TENANT_NAME = "USP-SIP-IC-24335-T-01"; + public static final String AIC_ZONE_ID = "NFT1"; + public static final String AIC_ZONE_NAME = "NFTJSSSS-NFT1"; + + protected HashMap<String, String> instanceParamsMapWithoutParams; + protected HashMap<String, String> vfModuleInstanceParamsMapWithParamsToRemove; + protected HashMap<String, String> vnfInstanceParamsMapWithParamsToRemove; + + @Inject + protected FeatureManager featureManager; + + @Inject + protected AaiClientInterface aaiClient; + + public ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure) { + ModelInfo modelInfo = createModelInfo(); + + List<Map<String,String>> instanceParams = createInstanceParams(); + + return new ServiceInstantiation ( + modelInfo, + AsyncInstantiationBusinessLogicTest.OWNING_ENTITY_ID, + AsyncInstantiationBusinessLogicTest.PACKET_CORE, + projectName, + AsyncInstantiationBusinessLogicTest.SUBSCRIBER_ID, + AsyncInstantiationBusinessLogicTest.SUBSCRIBER_NAME, + AsyncInstantiationBusinessLogicTest.PRODUCT_FAMILY_ID, + isUserProvidedNaming ? AsyncInstantiationBusinessLogicTest.INSTANCE_NAME : "" , + isUserProvidedNaming, + AsyncInstantiationBusinessLogicTest.SUBSCRIPTION_SERVICE_TYPE, + AsyncInstantiationBusinessLogicTest.LCP_CLOUD_REGION_ID, + AsyncInstantiationBusinessLogicTest.A6CA3EE0394ADE9403F075DB23167E, + AsyncInstantiationBusinessLogicTest.TENANT_NAME, + AsyncInstantiationBusinessLogicTest.AIC_ZONE_ID, + AsyncInstantiationBusinessLogicTest.AIC_ZONE_NAME, + vnfs, + instanceParams, + isPause, + bulkSize, + rollbackOnFailure + ); + } + + private List<Map<String,String>> createInstanceParams() { + List<Map<String, String>> instanceParams = new ArrayList<>(); + HashMap<String, String> map = new HashMap<>(); + map.put("instanceParams_test1" , "some text"); + map.put("instanceParams_test2" , "another text"); + instanceParams.add(map); + return instanceParams; + } + + private VfModule createVfModule(String modelName, String modelVersionId, String modelCustomizationId, + List<Map<String, String>> instanceParams, String instanceName, String volumeGroupInstanceName) { + ModelInfo vfModuleInfo = new ModelInfo(); + vfModuleInfo.setModelType("vfModule"); + vfModuleInfo.setModelName(modelName); + vfModuleInfo.setModelVersionId(modelVersionId); + vfModuleInfo.setModelCustomizationId(modelCustomizationId); + return new VfModule(vfModuleInfo , instanceName, volumeGroupInstanceName, instanceParams); + } + + private ModelInfo createVnfModelInfo() { + ModelInfo vnfModelInfo = new ModelInfo(); + vnfModelInfo.setModelType("vnf"); + vnfModelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L"); + vnfModelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8"); + vnfModelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0"); + vnfModelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04"); + return vnfModelInfo; + } + + private ModelInfo createModelInfo() { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType("service"); + modelInfo.setModelVersionId("3c40d244-808e-42ca-b09a-256d83d19d0a"); + modelInfo.setModelVersion("10.0"); + modelInfo.setModelInvariantId("5d48acb5-097d-4982-aeb2-f4a3bd87d31b"); + modelInfo.setModelName("MOW AVPN vMX BV vPE 1 Service"); + return modelInfo; + } + + protected Map<String, Vnf> createVnfList(HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams, boolean isUserProvidedNaming) { + Map<String, Vnf> vnfs = new HashMap<>(); + ModelInfo vnfModelInfo = createVnfModelInfo(); + + Map<String, Map<String, VfModule>> vfModules = new HashMap<>(); + + List<Map<String, String>> instanceParams1 =ImmutableList.of((ImmutableMap.of("vmx_int_net_len", "24"))); + VfModule vfModule1 = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", "4c75f813-fa91-45a4-89d0-790ff5f1ae79", "a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f", instanceParams1, "vmxnjr001_AVPN_base_vPE_BV_base", null); + List<Map<String, String>> instanceParams2 = ImmutableList.of(vfModuleInstanceParamsMap); + VfModule vfModule2 = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240", "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams2, "vmxnjr001_AVPN_base_vRE_BV_expansion", "myVgName"); + + String vfModuleModelName = vfModule1.getModelInfo().getModelName(); + vfModules.put(vfModuleModelName, new LinkedHashMap<>()); + + vfModules.get(vfModuleModelName).put(vfModule1.getInstanceName(),vfModule1); + vfModules.get(vfModuleModelName).put(vfModule2.getInstanceName(), vfModule2); + + Vnf vnf = new Vnf(vnfModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", "vmxnjr001", isUserProvidedNaming, + "platformName", "mdt1", "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" ,vfModules); + + vnfs.put(vnf.getInstanceName(), vnf); + return vnfs; + } + + protected void createInstanceParamsMaps() { + instanceParamsMapWithoutParams = new HashMap<>(); + instanceParamsMapWithoutParams.put("availability_zone_0" , "mtpocdv-kvm-az01"); + instanceParamsMapWithoutParams.put("vre_a_volume_size_0" , "100"); + + vfModuleInstanceParamsMapWithParamsToRemove = new HashMap<>(); + vfModuleInstanceParamsMapWithParamsToRemove.put(AsyncInstantiationBusinessLogic.PARAMS_TO_IGNORE.get(0), "should be removed"); + vfModuleInstanceParamsMapWithParamsToRemove.put("availability_zone_0" , "mtpocdv-kvm-az01"); + vfModuleInstanceParamsMapWithParamsToRemove.put("vre_a_volume_size_0" , "100"); + + vnfInstanceParamsMapWithParamsToRemove = new HashMap<>(); + vnfInstanceParamsMapWithParamsToRemove.put(AsyncInstantiationBusinessLogic.PARAMS_TO_IGNORE.get(1), "should be removed"); + } + + protected AsyncRequestStatus asyncRequestStatusResponse(String msoStatus) { + AsyncRequestStatus asyncRequestStatus = new AsyncRequestStatus(new AsyncRequestStatus.Request(new RequestStatus())); + asyncRequestStatus.request.requestStatus.setRequestState(msoStatus); + asyncRequestStatus.request.requestId = UUID.randomUUID().toString(); + return asyncRequestStatus; + } + + protected RestObject<AsyncRequestStatus> asyncRequestStatusResponseAsRestObject(String msoStatus) { + return asyncRequestStatusResponseAsRestObject(msoStatus, 200); + } + + protected RestObject<AsyncRequestStatus> asyncRequestStatusResponseAsRestObject(String msoStatus, int httpStatusCode) { + RestObject<AsyncRequestStatus> restObject = new RestObject<>(); + restObject.set(asyncRequestStatusResponse(msoStatus)); + restObject.setStatusCode(httpStatusCode); + return restObject; + } + + protected void mockAaiClientAnyNameFree() { + when(aaiClient.searchNodeTypeByName(any(), any())).thenReturn(aaiNodeQueryResponseNameFree()); + } + + protected AaiResponse<AaiNodeQueryResponse> aaiNodeQueryResponseNameFree() { + return new AaiResponse<>(new AaiNodeQueryResponse(null),"", 200); + } + + protected AaiResponse<AaiNodeQueryResponse> aaiNodeQueryBadResponse() { + return new AaiResponse<>(null,"", 404); + } + + protected AaiResponse<AaiNodeQueryResponse> aaiNodeQueryResponseNameUsed(ResourceType type) { + AaiNodeQueryResponse mockAaiNodeQuery = new AaiNodeQueryResponse(ImmutableList.of(new AaiNodeQueryResponse.ResultData(type, "/some/mocked/link"))); + return new AaiResponse<>(mockAaiNodeQuery,"", 200); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java new file mode 100644 index 00000000..7feb3704 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java @@ -0,0 +1,882 @@ +package org.onap.vid.services; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jersey.repackaged.com.google.common.collect.ImmutableList; +import net.javacrumbs.jsonunit.JsonAssert; +import org.apache.commons.io.IOUtils; +import org.hibernate.SessionFactory; +import org.json.JSONException; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.exceptions.InvalidAAIResponseException; +import org.onap.vid.aai.model.ResourceType; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.MaxRetriesException; +import org.onap.vid.exceptions.OperationNotAllowedException; +import org.onap.vid.job.Job; +import org.onap.vid.job.Job.JobStatus; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.impl.JobDaoImpl; +import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.model.JobAuditStatus.SourceStatus; +import org.onap.vid.model.NameCounter; +import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.model.serviceInstantiation.Vnf; +import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.utils.DaoUtils; +import org.onap.vid.config.DataSourceConfig; +import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; +import org.onap.vid.mso.MsoOperationalEnvironmentTest; +import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.portalsdk.core.FusionObject; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.testng.Assert; +import org.testng.annotations.*; + +import javax.inject.Inject; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URL; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.*; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.core.Every.everyItem; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; +import static org.onap.vid.job.Job.JobStatus.*; +import static org.testng.Assert.*; + +@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class}) +public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest { +/* +TO BE FIXED + @Inject + private DataAccessService dataAccessService; + + @Mock + private JobAdapter jobAdapter; + + @Mock + private JobsBrokerService jobsBrokerService; + + + + @Autowired + private SessionFactory sessionFactory; + + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + private int serviceCount = 0; + + private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE = + "Failed to retrieve job with uuid .* from ServiceInfo table. Instances found: .*"; + + private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE = + "Service status does not allow deletion from the queue"; + + @BeforeClass + void initServicesInfoService() { + MockitoAnnotations.initMocks(this); + asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient); + createInstanceParamsMaps(); + } + + @BeforeMethod + void defineMocks() { + mockAaiClientAnyNameFree(); + } + + @BeforeMethod + void resetServiceCount() { + serviceCount = 0; + } + + @AfterMethod + void clearDb() { + dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", getPropsMap()); + dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", getPropsMap()); + dataAccessService.deleteDomainObjects(JobAuditStatus.class, "1=1", getPropsMap()); + dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", getPropsMap()); + } + + + private void createNewTestServicesInfoForFilter(String userId) { + LocalDateTime createdDate, modifiedDate; + LocalDateTime NOW = LocalDateTime.now(); + UUID uuid; + + // Old job + uuid = UUID.randomUUID(); + addNewJob(uuid); + createdDate = NOW.minusYears(1); + addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false); + + uuid = UUID.randomUUID(); + addNewJob(uuid); + createdDate = NOW.minusDays(20); + modifiedDate = NOW.minusDays(19); + addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true); + + createNewTestServicesInfo(String.valueOf(userId)); + } + + private void createNewTestServicesInfo(String userId) { + + LocalDateTime createdDate, modifiedDate; + LocalDateTime NOW = LocalDateTime.now(); + UUID uuid; + + uuid = UUID.randomUUID(); + addNewJob(uuid); + + createdDate = NOW.minusDays(40); + addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false); + addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false); + + uuid = UUID.randomUUID(); + addNewJob(uuid); + + createdDate = NOW.minusDays(20); + modifiedDate = NOW.minusDays(10); + addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false); + addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false); + addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false); + + modifiedDate = NOW.minusDays(19); + addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false); + + + // Job to a different user + uuid = UUID.randomUUID(); + addNewJob(uuid); + + createdDate = NOW.minusMonths(2); + addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false); + + } + + private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) { + + LocalDateTime NOW = LocalDateTime.now(); + UUID uuid; + + uuid = UUID.randomUUID(); + addNewJob(uuid, status); + + addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false); + + return uuid; + + } + + private List<ServiceInfo> getFullList() { + List<ServiceInfo> expectedOrderServiceInfo = dataAccessService.getList(ServiceInfo.class, getPropsMap()); + assertThat("Failed to retrieve all predefined services", expectedOrderServiceInfo.size(), equalTo(serviceCount)); + expectedOrderServiceInfo.sort(new ServiceInfoComparator()); + return expectedOrderServiceInfo; + } + + private static Date toDate(LocalDateTime localDateTime) { + return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); + } + + private LocalDateTime fromDate(Date date) { + return Instant.ofEpochMilli(date.getTime()) + .atZone(ZoneId.systemDefault()) + .toLocalDateTime(); + } + + private void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, LocalDateTime statusModifiedDate, Job.JobStatus status, boolean isHidden) { + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setJobId(uuid); + serviceInfo.setUserId(userId); + serviceInfo.setServiceInstanceName(serviceName); + serviceInfo.setStatusModifiedDate(toDate(statusModifiedDate)); + serviceInfo.setJobStatus(status); + serviceInfo.setPause(false); + serviceInfo.setOwningEntityId("1234"); + serviceInfo.setCreatedBulkDate(toDate(createDate)); + + serviceInfo.setHidden(isHidden); + dataAccessService.saveDomainObject(serviceInfo, getPropsMap()); + setCreateDateToServiceInfo(uuid, createDate); + serviceCount++; + + } + + private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) { + List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); + DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { + serviceInfoList.stream() + .filter(serviceInfo -> jobUuid.equals(serviceInfo.getJobId())) + .forEach(serviceInfo -> { + serviceInfo.setCreated(toDate(createDate)); + session.saveOrUpdate(serviceInfo); + }); + return 1; + }); + } + + private void addNewJob(UUID uuid) { + addNewJob(uuid, null); + } + + private void addNewJob(UUID uuid, Job.JobStatus status) { + JobDaoImpl jobDao = new JobDaoImpl(); + jobDao.setUuid(uuid); + jobDao.setStatus(status); + dataAccessService.saveDomainObject(jobDao, getPropsMap()); + } + + @Test + public void testServiceInfoAreOrderedAsExpected() { + int userId = 2222; + createNewTestServicesInfo(String.valueOf(userId)); + List<ServiceInfo> expectedOrderServiceInfo = getFullList(); + List<ServiceInfo> serviceInfoListResult = asyncInstantiationBL.getAllServicesInfo(); + assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo)); + } + + @Test + public void testServiceInfoAreFilteredAsExpected() { + int userId = 2222; + createNewTestServicesInfoForFilter(String.valueOf(userId)); + List<ServiceInfo> expectedOrderServiceInfo = getFullList(); + + List<ServiceInfo> expectedFilterByUser = expectedOrderServiceInfo.stream().filter(x -> + !x.getServiceInstanceName().equals("Old") && !x.getServiceInstanceName().equals("Hidden") + + ).collect(Collectors.toList()); + + + List<ServiceInfo> serviceInfoFilteredByUser = asyncInstantiationBL.getAllServicesInfo(); + assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser)); + } + + @Test(dataProvider = "pauseAndInstanceParams", enabled = false) //Test is irrelevant with unique names feature + public void createServiceInstantiationMsoRequest(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception { + ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true)); + final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request.json"); + RequestDetailsWrapper<ServiceInstantiationRequestDetails> result = + asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); + String expected = IOUtils.toString(resource, "UTF-8"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test(dataProvider = "pauseAndInstanceParams") + public void createServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception { + Mockito.reset(aaiClient); + mockAaiClientAnyNameFree(); + ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true)); + final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json"); + List<UUID> uuids = new ArrayList<>(); + for (int i = 0; i < 2; i++) { + UUID currentUuid = createJobAndServiceInfo(); + uuids.add(currentUuid); + RequestDetailsWrapper<ServiceInstantiationRequestDetails> result = + asyncInstantiationBL.generateServiceInstantiationRequest(currentUuid, serviceInstantiationPayload, "az2016"); + String unique = String.format("00%s", i + 1); + String expected = IOUtils.toString(resource, "UTF-8") + .replace("{SERVICE_UNIQENESS}", unique) + .replace("{VNF_UNIQENESS}", unique) + .replace("{VF_MODULE_UNIQENESS}", unique) + .replace("{VF_MODULE_2_UNIQENESS}", unique) + .replace("{VG_UNIQUENESS}", unique); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + Optional<ServiceInfo> optionalServiceInfo = getJobById(currentUuid); + assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service_" + unique)); + verifySearchNodeTypeByName(unique, "vPE_Service_", ResourceType.SERVICE_INSTANCE); + verifySearchNodeTypeByName(unique, "vmxnjr001_", ResourceType.GENERIC_VNF); + verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base_", ResourceType.VF_MODULE); + verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion_", ResourceType.VF_MODULE); + verifySearchNodeTypeByName(unique, "myVgName_", ResourceType.VOLUME_GROUP); + } + } + + protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) { + verify(aaiClient, times(1)).searchNodeTypeByName(resourceName + unique, serviceInstance); + } + + private HashMap<String, Object> getPropsMap() { + HashMap<String, Object> props = new HashMap<>(); + props.put(FusionObject.Parameters.PARAM_USERID, 0); + return props; + } + + @Test(enabled = false) //probably not needed with name uniqueness feature + public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected() { + int bulkSize = 3; + + final ServiceInstantiation request = generateMockServiceInstantiationPayload( + false, + createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), + bulkSize, true,PROJECT_NAME, true + ); + + // in "createJob()" we will probe the service, with the generated names + final Job job = mock(Job.class); + when(job.getStatus()).thenReturn(PENDING); + when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job); + + + final List<UUID> uuids = asyncInstantiationBL.pushBulkJob(request, "myUserId"); + + + ArgumentCaptor<ServiceInstantiation> serviceInstantiationCaptor = new ArgumentCaptor<ServiceInstantiation>(); + verify(jobAdapter, times(bulkSize)).createJob(any(), serviceInstantiationCaptor.capture(), any(), any(), any()); + + assertThat(serviceInstantiationCaptor.getAllValues().stream().map(v -> v.getInstanceName()).collect(Collectors.toList()), + containsInAnyOrder("vPE_Service_001", "vPE_Service_002", "vPE_Service_003")); + + assertThat(uuids, hasSize(bulkSize)); + } + + @Test + public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame() throws IOException { + ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload( + false, + createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true), + 2, false,PROJECT_NAME, false); + ObjectMapper mapper = new ObjectMapper(); + final String asString = mapper.writeValueAsString(serviceInstantiationPayload); + + final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class); + final String asString2 = mapper.writeValueAsString(asObject); + + JsonAssert.assertJsonEquals(asString, asString2); + } + + public static class ServiceInfoComparator implements Comparator<ServiceInfo> { + + @Override + public int compare(ServiceInfo o1, ServiceInfo o2) { + int compare; + + compare = o1.getCreatedBulkDate().compareTo(o2.getCreatedBulkDate()); + if (compare != 0) { + return -compare; + } + + // check jobStatus priority + int o1Priority = getPriority(o1); + int o2Priority = getPriority(o2); + compare = o1Priority - o2Priority; + if (compare != 0) { + return compare; + } + + // check statusModifiedDate + return o1.getStatusModifiedDate().compareTo(o2.getStatusModifiedDate()); + } + + private int getPriority(ServiceInfo o) throws JSONException { + Job.JobStatus status = o.getJobStatus(); + switch (status) { + case COMPLETED: + case FAILED: + return 1; + case IN_PROGRESS: + return 2; + case PAUSE: + return 3; + case STOPPED: + case PENDING: + return 4; + default: + return 5; + } + } + } + + @DataProvider + public Object[][] pauseAndInstanceParams() { + return new Object[][]{ + {Boolean.TRUE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST}, + {Boolean.FALSE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST}, + {Boolean.TRUE, vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove)} + }; + } + + private ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs) { + return generateMockServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false); + } + + @Test + public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() { + UUID uuid = createJobAndServiceInfo(); + final String STEPH_CURRY = "Steph Curry"; + asyncInstantiationBL.updateServiceInfo(uuid, x -> { + x.setServiceInstanceName(STEPH_CURRY); + x.setJobStatus(Job.JobStatus.IN_PROGRESS); + }); + Optional<ServiceInfo> optionalServiceInfo = getJobById(uuid); + assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo(STEPH_CURRY)); + assertThat(optionalServiceInfo.get().getJobStatus(), equalTo(Job.JobStatus.IN_PROGRESS)); + } + + private Optional<ServiceInfo> getJobById(UUID jobId) { + List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, null); + return serviceInfoList.stream().filter(x -> jobId.equals(x.getJobId())).findFirst(); + } + + private UUID createJobAndServiceInfo() { + UUID uuid = UUID.randomUUID(); + addNewJob(uuid); + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setServiceInstanceName("Lebron James"); + serviceInfo.setJobId(uuid); + serviceInfo.setJobStatus(Job.JobStatus.PENDING); + dataAccessService.saveDomainObject(serviceInfo, getPropsMap()); + return uuid; + } + + @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) + public void testUpdateServiceInfo_WithNonExisting_ThrowException() { + asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter")); + } + + @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) + public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() { + UUID uuid = createJobAndServiceInfo(); + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setJobId(uuid); + dataAccessService.saveDomainObject(serviceInfo, getPropsMap()); + asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter")); + } + + + + @Test + public void testRequestPath_WithPauseFlagTrue_RequestPathIsAsExpected() { + ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMockServiceInstantiationPayload(true, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true)); + String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagTrue); + Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceAssign")); + } + + @Test + public void testRequestPath_WithPauseFlagFalse_RequestPathIsAsExpected() { + ServiceInstantiation serviceInstantiationPauseFlagFalse = generateMockServiceInstantiationPayload(false, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true)); + String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagFalse); + Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceCreate")); + } + + @Test + public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException { + createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true); + } + + @Test + public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException { + createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false); + } + + private void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException { + ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true, + createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), + 1, + false,PROJECT_NAME, true); + URL resource; + if (withVfmodules) { + resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json"); + } else { + // remove the vf modules + serviceInstantiationPayload.getVnfs().values().forEach(vnf -> vnf.getVfModules().clear()); + resource = this.getClass().getResource("/payload_jsons/bulk_service_request_no_vfmodule_ecomp_naming.json"); + } + + RequestDetailsWrapper<ServiceInstantiationRequestDetails> result = + asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); + + String expected = IOUtils.toString(resource, "UTF-8"); + MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + } + + @Test + public void checkIfNullProjectNameSentToMso(){ + ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true, + createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), + 1, + false,null,false); + RequestDetailsWrapper<ServiceInstantiationRequestDetails> result = + asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); + JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails); + Assert.assertTrue(jsonNode.get("project").isNull()); + serviceInstantiationPayload = generateMockServiceInstantiationPayload(true, + createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), + 1, + false,"not null",false); + result = asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016"); + jsonNode = new ObjectMapper().valueToTree(result.requestDetails); + Assert.assertTrue(jsonNode.get("project").get("projectName").asText().equalsIgnoreCase("not null")); + + + + } + + @Test + public void pushBulkJob_verifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() { + LocalDateTime startTestDate = LocalDateTime.now().withNano(0); + final ServiceInstantiation request = generateMockServiceInstantiationPayload( + false, + createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), + 100, true,PROJECT_NAME, true + ); + + // in "createJob()" we will probe the service, with the generated names + final Job job = mock(Job.class); + when(job.getStatus()).thenReturn(PENDING); + when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job); + + asyncInstantiationBL.pushBulkJob(request, "myUserId"); + List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); + + List<Date> creationDates = new ArrayList<>(); + for (ServiceInfo serviceInfo : serviceInfoList) { + creationDates.add(serviceInfo.getCreatedBulkDate()); + } + LocalDateTime endTestDate = LocalDateTime.now(); + + //creation date of all services is the same + Assert.assertTrue(creationDates.stream().distinct().count() <= 1); + LocalDateTime creationDate = fromDate(creationDates.get(0)); + assertFalse(creationDate.isBefore(startTestDate)); + assertFalse(creationDate.isAfter(endTestDate)); + } + + @DataProvider + public static Object[][] msoToJobStatusDataProvider() { + return new Object[][]{ + {"IN_PROGRESS", JobStatus.IN_PROGRESS}, + {"INPROGRESS", JobStatus.IN_PROGRESS}, + {"IN ProGREsS", JobStatus.IN_PROGRESS}, + {"JAMES_HARDEN", JobStatus.IN_PROGRESS}, + {"FAILED", JobStatus.FAILED}, + {"COMpleTE", JobStatus.COMPLETED}, + {"PENDING", JobStatus.IN_PROGRESS}, + {"Paused", JobStatus.PAUSE}, + {"Pause", JobStatus.PAUSE}, + {"PENDING_MANUAL_TASK", JobStatus.PAUSE}, + {"UNLOCKED", JobStatus.IN_PROGRESS} + }; + } + + @Test(dataProvider = "msoToJobStatusDataProvider") + void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) { + AsyncRequestStatus asyncRequestStatus = asyncRequestStatusResponse(msoStatus); + assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus)); + } + + private void createNewAuditStatus(JobAuditStatus auditStatus) + { + Date createdDate= auditStatus.getCreated(); + dataAccessService.saveDomainObject(auditStatus, getPropsMap()); + setDateToStatus(auditStatus.getSource(), auditStatus.getJobStatus(), createdDate); + } + + + + private static final String MSO_ARBITRARY_STATUS = "completed mso status"; + + @DataProvider + public static Object[][] auditStatuses(Method test) { + return new Object[][]{ + { + SourceStatus.VID, + new String[]{ JobStatus.PENDING.toString(), JobStatus.IN_PROGRESS.toString()} + }, + { SourceStatus.MSO, + new String[]{ JobStatus.IN_PROGRESS.toString(), MSO_ARBITRARY_STATUS } + } + }; + + } + + private void setDateToStatus(SourceStatus source, String status, Date date) { + List<JobAuditStatus> jobAuditStatusList = dataAccessService.getList(JobAuditStatus.class, getPropsMap()); + DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { + jobAuditStatusList.stream() + .filter(auditStatus -> source.equals(auditStatus.getSource()) && status.equals(auditStatus.getJobStatus())) + .forEach(auditStatus -> { + auditStatus.setCreated(date); + session.saveOrUpdate(auditStatus); + }); + return 1; + }); + } + + + @Test(dataProvider = "auditStatuses") + public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(SourceStatus expectedSource, String [] expectedSortedStatuses){ + UUID jobUuid = UUID.randomUUID(); + List<JobAuditStatus> auditStatusList = com.google.common.collect.ImmutableList.of( + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(2))), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(30))), + new JobAuditStatus(jobUuid, MSO_ARBITRARY_STATUS, SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(3))), + new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))), + new JobAuditStatus(UUID.randomUUID(), PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3)))); + auditStatusList.forEach((auditStatus) -> createNewAuditStatus(auditStatus)); + List<JobAuditStatus> statuses = asyncInstantiationBL.getAuditStatuses(jobUuid, expectedSource); + List<String> statusesList = statuses.stream().map(status -> status.getJobStatus()).collect(Collectors.toList()); + Assert.assertTrue(statuses.stream().allMatch(status -> (status.getSource().equals(expectedSource)&& status.getJobId().equals(jobUuid))),"Only statuses of " + expectedSource + " for " + jobUuid + " should be returned. Returned statuses: " + String.join(",", statusesList )); + assertThat(statusesList, contains(expectedSortedStatuses)); + } + + + + @Test + public void addSomeVidStatuses_getThem_verifyGetInsertedWithoutDuplicates(){ + ImmutableList<JobStatus> statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED); + UUID jobUuid = UUID.randomUUID(); + statusesToBeInserted.forEach(status-> + { + asyncInstantiationBL.auditVidStatus(jobUuid, status); + }); + List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.VID).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList()); + List<String> statusesWithoutDuplicates = statusesToBeInserted.stream().distinct().map(x -> x.toString()).collect(Collectors.toList()); + assertThat(statusesFromDB, is(statusesWithoutDuplicates)); + } + + @DataProvider + public static Object[][] msoAuditStatuses(Method test) { + UUID jobUuid = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + return new Object[][]{ + { + jobUuid, + ImmutableList.of( + new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), + new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)), + ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), COMPLETED.toString()), + "All distinct statuses should be without duplicates" + }, + { + jobUuid, + ImmutableList.of( + new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"), + new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(), "aa"), + new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)), + ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), IN_PROGRESS.toString(),IN_PROGRESS.toString(), COMPLETED.toString()), + "Statuses should be without duplicates only with same requestId and additionalInfo" + + } + }; + } + + @Test(dataProvider = "msoAuditStatuses") + public void addSomeMsoStatuses_getThem_verifyGetInsertedWithoutDuplicates(UUID jobUuid, ImmutableList<JobAuditStatus> msoStatuses, ImmutableList<String> expectedStatuses, String assertionReason) { + msoStatuses.forEach(status -> { + asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo()); + }); + List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.MSO).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList()); + assertThat( assertionReason, statusesFromDB, is(expectedStatuses)); + } + + @Test + public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){ + UUID jobUuid = UUID.randomUUID(); + JobStatus sameStatus = IN_PROGRESS; + asyncInstantiationBL.auditMsoStatus(jobUuid, sameStatus.toString(),null,null); + asyncInstantiationBL.auditVidStatus(jobUuid, sameStatus); + List<JobAuditStatus> list = dataAccessService.getList( + JobAuditStatus.class, + String.format(" where JOB_ID = '%s'", jobUuid), + null, null); + Assert.assertEquals(list.size(),2); + assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString())))); + } + + @Test + public void verifyAsyncRequestStatus_canBeReadFromSample() throws IOException { + String body = "{" + + " \"request\": {" + + " \"requestId\": \"c0011670-0e1a-4b74-945d-8bf5aede1d9c\"," + + " \"startTime\": \"Mon, 11 Dec 2017 07:27:49 GMT\"," + + " \"requestScope\": \"service\"," + + " \"requestType\": \"createInstance\"," + + " \"instanceReferences\": {" + + " \"serviceInstanceId\": \"f8791436-8d55-4fde-b4d5-72dd2cf13cfb\"," + + " \"serviceInstanceName\": \"asdfasdf234234asdf\"," + + " \"requestorId\": \"il883e\"" + + " }," + + " \"requestStatus\": {" + + " \"requestState\": \"COMPLETE\"," + + " \"statusMessage\": \"Service Instance was created successfully.\"," + + " \"percentProgress\": 100," + + " \"finishTime\": \"Mon, 11 Dec 2017 07:27:53 GMT\"" + + " }" + + " }" + + "}"; + ObjectMapper objectMapper = new ObjectMapper(); + AsyncRequestStatus asyncRequestStatus = objectMapper.readValue(body, AsyncRequestStatus.class); + assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE")); + + } + + @Test + public void deleteJobInfo_pending_deleted() { + doNothing().when(jobsBrokerService).delete(any()); + UUID uuid = createServicesInfoWithDefaultValues(PENDING); + asyncInstantiationBL.deleteJob(uuid); + assertNotNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted"); + } + + @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE) + public void deleteJobInfo_notAllowdStatus_shouldSendError() { + UUID uuid = createServicesInfoWithDefaultValues(COMPLETED); + doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerService).delete(any()); + try { + asyncInstantiationBL.deleteJob(uuid); + } catch (Exception e) { + assertNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted"); + throw e; + } + } + + @DataProvider + public Object[][] jobStatusesFinal() { + return Arrays.stream(Job.JobStatus.values()) + .filter(t -> ImmutableList.of(COMPLETED, FAILED, STOPPED).contains(t)) + .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{}); + } + + @Test(dataProvider = "jobStatusesFinal") + public void whenHideService_theServiceNotReturnedInServiceList(JobStatus jobStatus) { + UUID uuidToHide = createServicesInfoWithDefaultValues(jobStatus); + UUID uuidToShown = createServicesInfoWithDefaultValues(jobStatus); + List<UUID> serviceInfoList = listServicesUUID(); + assertThat(serviceInfoList, hasItems(uuidToHide, uuidToShown)); + + asyncInstantiationBL.hideServiceInfo(uuidToHide); + serviceInfoList = listServicesUUID(); + assertThat(serviceInfoList, hasItem(uuidToShown)); + assertThat(serviceInfoList, not(hasItem(uuidToHide))); + + } + + protected List<UUID> listServicesUUID() { + return asyncInstantiationBL.getAllServicesInfo().stream().map(ServiceInfo::getJobId).collect(Collectors.toList()); + } + + @DataProvider + public Object[][] jobStatusesNotFinal() { + return Arrays.stream(Job.JobStatus.values()) + .filter(t -> ImmutableList.of(PENDING, IN_PROGRESS, PAUSE).contains(t)) + .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{}); + } + + @Test( dataProvider = "jobStatusesNotFinal", + expectedExceptions = OperationNotAllowedException.class, + expectedExceptionsMessageRegExp = "jobId.*Service status does not allow hide service, status = .*") + public void hideServiceInfo_notAllowedStatus_shouldSendError(JobStatus jobStatus) { + UUID uuid = createServicesInfoWithDefaultValues(jobStatus); + try { + asyncInstantiationBL.hideServiceInfo(uuid); + } catch (Exception e) { + assertFalse(asyncInstantiationBL.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden"); + throw e; + } + } + + @Test + public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException { + int SIZE = 200; + ExecutorService executor = Executors.newFixedThreadPool(SIZE); + List<Callable<Integer>> tasks = IntStream.rangeClosed(1, SIZE) + .mapToObj(x-> ((Callable<Integer>)() -> asyncInstantiationBL.getCounterForName("a"))) + .collect(Collectors.toList()); + Set<Integer> expectedResults = IntStream.rangeClosed(1, SIZE).boxed().collect(Collectors.toSet()); + executor.invokeAll(tasks) + .forEach(future -> { + try { + assertTrue( expectedResults.remove(future.get()), "got unexpected counter"); + } + catch (Exception e) { + throw new RuntimeException(e); + } + }); + + assertThat(expectedResults.size(), is(0)); + } + + @Test + public void whenUseGetCounterForSameName_numbersReturnedByOrder() { + + String name = UUID.randomUUID().toString(); + int SIZE=10; + for (int i=1; i<=SIZE; i++) { + assertThat(asyncInstantiationBL.getCounterForName(name), is(i)); + } + } + + @Test + public void whenNamedInUsedInAai_getNextNumber() { + String name = someCommonStepsAndGetName(); + ResourceType type = ResourceType.GENERIC_VNF; + when(aaiClient.searchNodeTypeByName(name+"_001", type)).thenReturn(aaiNodeQueryResponseNameUsed(type)); + when(aaiClient.searchNodeTypeByName(name+"_002", type)).thenReturn(aaiNodeQueryResponseNameFree()); + assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_002")); + } + + private String someCommonStepsAndGetName() { + mockAaiClientAaiStatusOK(); + return UUID.randomUUID().toString(); + } + + private void mockAaiClientAaiStatusOK() { + when(aaiClient.searchNodeTypeByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(aaiNodeQueryResponseNameFree()); + } + + @Test(expectedExceptions=InvalidAAIResponseException.class) + public void whenAaiBadResponseCode_throwInvalidAAIResponseException() { + String name = someCommonStepsAndGetName(); + ResourceType type = ResourceType.SERVICE_INSTANCE; + when(aaiClient.searchNodeTypeByName(name+"_001", type)).thenReturn(aaiNodeQueryBadResponse()); + asyncInstantiationBL.getUniqueName(name, type); + } + + @Test(expectedExceptions=MaxRetriesException.class) + public void whenAaiAlwaysReturnNameUsed_throwInvalidAAIResponseException() { + String name = someCommonStepsAndGetName(); + ResourceType type = ResourceType.VF_MODULE; + when(aaiClient.searchNodeTypeByName(any(), eq(type))).thenReturn(aaiNodeQueryResponseNameUsed(type)); + asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10); + asyncInstantiationBL.getUniqueName(name, type); + } + + @Test + public void testFormattingOfNameAndCounter() { + AsyncInstantiationBusinessLogicImpl bl = (AsyncInstantiationBusinessLogicImpl) asyncInstantiationBL; + assertThat(bl.formatNameAndCounter("x", 3), equalTo("x_003")); + assertThat(bl.formatNameAndCounter("x", 99), equalTo("x_099")); + assertThat(bl.formatNameAndCounter("x", 100), equalTo("x_100")); + assertThat(bl.formatNameAndCounter("x", 1234), equalTo("x_1234")); + }*/ +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java index 7819b4c9..157f59c7 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceImplTest.java @@ -1,193 +1,116 @@ package org.onap.vid.services; -import static org.junit.Assert.*; -import java.util.*; - -import org.json.simple.JSONArray; -import org.junit.Assert; -import org.junit.Test; -import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.mockito.*; import org.onap.vid.changeManagement.ChangeManagementRequest; -import org.onap.vid.changeManagement.GetVnfWorkflowRelationRequest; import org.onap.vid.changeManagement.RequestDetails; -import org.onap.vid.changeManagement.VnfWorkflowRelationAllResponse; -import org.onap.vid.changeManagement.VnfWorkflowRelationRequest; -import org.onap.vid.changeManagement.VnfWorkflowRelationResponse; import org.onap.vid.mso.MsoBusinessLogic; -import org.onap.vid.mso.MsoBusinessLogicImpl; -import org.onap.vid.mso.rest.MsoRestClientNew; -import org.onap.vid.mso.rest.Request; +import org.onap.vid.mso.MsoResponseWrapperInterface; +import org.onap.vid.scheduler.SchedulerRestInterfaceIfc; +import org.onap.portalsdk.core.service.DataAccessService; import org.springframework.http.ResponseEntity; -import org.springframework.web.multipart.MultipartFile; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import static org.mockito.Mockito.verify; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +@Test public class ChangeManagementServiceImplTest { - private ChangeManagementServiceImpl createTestSubject() { - return new ChangeManagementServiceImpl(new DataAccessServiceImpl(), - new MsoBusinessLogicImpl(new MsoRestClientNew())); - } + @Mock + DataAccessService dataAccessServiceMock; - @Test - public void testGetMSOChangeManagements() throws Exception { - ChangeManagementServiceImpl testSubject; - Collection<Request> result; + @Mock + MsoBusinessLogic msoBusinessLogicMock; + + @Mock + SchedulerRestInterfaceIfc schedulerRestInterface; - // default test - testSubject = createTestSubject(); - result = testSubject.getMSOChangeManagements(); + @BeforeMethod + public void initMocks(){ + MockitoAnnotations.initMocks(this); } @Test - public void testDoChangeManagement() throws Exception { - ChangeManagementServiceImpl testSubject; - ChangeManagementRequest request = null; - String vnfName = ""; - ResponseEntity<String> result; - - // test 1 - testSubject = createTestSubject(); - request = null; - result = testSubject.doChangeManagement(request, vnfName); - Assert.assertEquals(null, result); + public void doChangeManagement_requestIsNull_returnsNull() throws Exception { + ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface); + ResponseEntity<String> result = changeManagementService.doChangeManagement(null,"anyString"); + assertNull(result); } @Test - public void testGetSchedulerChangeManagements() throws Exception { - ChangeManagementServiceImpl testSubject; - JSONArray result; + public void doChangeManagement_currentRequestDetailsIsNull_returnsNull() throws Exception { + ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface); - // default test - testSubject = createTestSubject(); - result = testSubject.getSchedulerChangeManagements(); - } + ChangeManagementServiceImpl changeManagementServiceSpied = Mockito.spy(changeManagementService); + Mockito.doReturn(null).when(changeManagementServiceSpied).findRequestByVnfName(Matchers.anyList(),Mockito.anyString()); - @Test - public void testDeleteSchedule() throws Exception { - ChangeManagementServiceImpl testSubject; - String scheduleId = ""; + ResponseEntity<String> result = changeManagementServiceSpied.doChangeManagement(null,"anyString"); - // default test - testSubject = createTestSubject(); - testSubject.deleteSchedule(scheduleId); + assertNull(result); } - @Test - public void testAddVnfWorkflowRelation() throws Exception { - ChangeManagementServiceImpl testSubject; - VnfWorkflowRelationRequest vnfWorkflowRelationRequest = null; - VnfWorkflowRelationResponse result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.addVnfWorkflowRelation(vnfWorkflowRelationRequest); - } catch ( - - Exception e) { - } - } @Test - public void testDeleteVnfWorkflowRelation() throws Exception { - ChangeManagementServiceImpl testSubject; - VnfWorkflowRelationRequest vnfWorkflowRelationRequest = null; - VnfWorkflowRelationResponse result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteVnfWorkflowRelation(vnfWorkflowRelationRequest); - } catch ( - - Exception e) { - } + public void doChangeManagement_requestTypeIsUpdate_MsoUpdateVnfIsCalled() throws Exception { + Mockito.doReturn(Mockito.mock(MsoResponseWrapperInterface.class)).when(msoBusinessLogicMock).updateVnf(Mockito.any(),Mockito.anyString(),Mockito.anyString()); + RequestDetails requestDetails = callChangeManagement(ChangeManagementRequest.UPDATE); + + ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); + verify(msoBusinessLogicMock).updateVnf(argumentCaptor.capture(),Mockito.anyString(),Mockito.anyString()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); } @Test - public void testGetAllVnfWorkflowRelations() throws Exception { - ChangeManagementServiceImpl testSubject; - VnfWorkflowRelationAllResponse result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getAllVnfWorkflowRelations(); - } catch ( - - Exception e) { - } + public void doChangeManagement_requestTypeIsReplace_MsoUpdateVnfIsCalled() throws Exception { + Mockito.doReturn(Mockito.mock(MsoResponseWrapperInterface.class)).when(msoBusinessLogicMock).replaceVnf(Mockito.any(),Mockito.anyString(),Mockito.anyString()); + RequestDetails requestDetails = callChangeManagement(ChangeManagementRequest.REPLACE); + + + ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); + + verify(msoBusinessLogicMock).replaceVnf(argumentCaptor.capture(),Mockito.anyString(),Mockito.anyString()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); } @Test - public void testGetWorkflowsForVnf() throws Exception { - ChangeManagementServiceImpl testSubject; - GetVnfWorkflowRelationRequest getVnfWorkflowRelationRequest = null; - List<String> result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.getWorkflowsForVnf(getVnfWorkflowRelationRequest); - } catch ( - - Exception e) { - } + public void doChangeManagement_requestTypeIsInPlaceSoftwareUpdate_MsoUpdateVnfIsCalled() throws Exception { + Mockito.doReturn(Mockito.mock(MsoResponseWrapperInterface.class)).when(msoBusinessLogicMock).updateVnfSoftware(Mockito.any(),Mockito.anyString(),Mockito.anyString()); + RequestDetails requestDetails = callChangeManagement(ChangeManagementRequest.VNF_IN_PLACE_SOFTWARE_UPDATE); + + + ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); + + verify(msoBusinessLogicMock).updateVnfSoftware(argumentCaptor.capture(),Mockito.anyString(),Mockito.anyString()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); } @Test - public void testUploadConfigUpdateFile() throws Exception { - ChangeManagementServiceImpl testSubject; - MultipartFile file = null; - String result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.uploadConfigUpdateFile(file); - } catch ( - - Exception e) { - } + public void doChangeManagement_requestTypeIsConfigUpdate_MsoUpdateVnfIsCalled() throws Exception { + Mockito.doReturn(Mockito.mock(MsoResponseWrapperInterface.class)).when(msoBusinessLogicMock).updateVnfConfig(Mockito.any(),Mockito.anyString(),Mockito.anyString()); + RequestDetails requestDetails = callChangeManagement(ChangeManagementRequest.CONFIG_UPDATE); + + + ArgumentCaptor<RequestDetails> argumentCaptor = ArgumentCaptor.forClass(RequestDetails.class); + + verify(msoBusinessLogicMock).updateVnfConfig(argumentCaptor.capture(),Mockito.anyString(),Mockito.anyString()); + assertEquals(argumentCaptor.getValue().getVnfInstanceId(),requestDetails.getVnfInstanceId()); } - /* - * TODO: fix private ChangeManagementServiceImpl createTestSubject() { - * return new ChangeManagementServiceImpl(); } - */ - - /* - * @Test public void testGetMSOChangeManagements() throws Exception { - * ChangeManagementServiceImpl testSubject; Collection<Request> result; - * - * // default test testSubject = createTestSubject(); result = - * testSubject.getMSOChangeManagements(); } - * - * - * @Test public void testFindRequestByVnfName() throws Exception { - * ChangeManagementServiceImpl testSubject;List<RequestDetails> requests = - * null; String vnfName = ""; RequestDetails result; - * - * // test 1 testSubject=createTestSubject();requests = null; - * result=Deencapsulation.invoke(testSubject, "findRequestByVnfName", new - * Object[]{List<RequestDetails>.class, vnfName}); Assert.assertEquals(null, - * result); } - */ - /* - * - * @Test public void testDoChangeManagement() throws Exception { - * ChangeManagementServiceImpl testSubject; ChangeManagementRequest request - * = null; String vnfName = ""; ResponseEntity<String> result; - * - * // test 1 testSubject = createTestSubject(); request = null; result = - * testSubject.doChangeManagement(request, vnfName); - * Assert.assertEquals(null, result); } - * - * - * @Test public void testGetSchedulerChangeManagements() throws Exception { - * ChangeManagementServiceImpl testSubject; JSONArray result; - * - * // default test testSubject = createTestSubject(); result = - * testSubject.getSchedulerChangeManagements(); } - */ -}
\ No newline at end of file + private RequestDetails callChangeManagement(String requestType) throws Exception { + ChangeManagementServiceImpl changeManagementService = new ChangeManagementServiceImpl(dataAccessServiceMock, msoBusinessLogicMock, schedulerRestInterface); + ChangeManagementServiceImpl changeManagementServiceSpied = Mockito.spy(changeManagementService); + ChangeManagementRequest updateRequest = new ChangeManagementRequest(); + + updateRequest.setRequestType(requestType); + RequestDetails requestDetails = new RequestDetails(); + requestDetails.setVnfInstanceId("vnfFakeId"); + Mockito.doReturn("fakeId").when(changeManagementServiceSpied).extractServiceInstanceId(Mockito.anyObject(),Mockito.anyString()); + Mockito.doReturn(requestDetails).when(changeManagementServiceSpied).findRequestByVnfName(Matchers.anyList(),Mockito.anyString()); + + changeManagementServiceSpied.doChangeManagement(updateRequest,"anyVnfName"); + + return requestDetails; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java index 26274e80..5a21d8ca 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java @@ -3,18 +3,21 @@ package org.onap.vid.services; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.IOUtils; import org.mockito.ArgumentCaptor; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.ChangeManagementRequest; import org.onap.vid.controllers.MsoConfig; import org.onap.vid.controllers.WebConfig; import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.properties.AsdcClientConfiguration; +import org.onap.vid.scheduler.SchedulerRestInterfaceIfc; import org.onap.vid.services.ChangeManagementService; import org.onap.vid.services.ChangeManagementServiceImpl; import org.onap.vid.testUtils.RegExMatcher; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; import org.skyscreamer.jsonassert.JSONAssert; import org.skyscreamer.jsonassert.JSONCompareMode; import org.springframework.context.annotation.Bean; @@ -100,8 +103,8 @@ public class ChangeManagementServiceUnitTest extends AbstractTestNGSpringContext } @Bean - public ChangeManagementService getChangeManagementService() { - return new ChangeManagementServiceImpl(null, getMsoBusinessLogic()); + public ChangeManagementService getChangeManagementService(DataAccessService dataAccessService, MsoBusinessLogic msoInterface, SchedulerRestInterfaceIfc schedulerRestInterface) { + return new ChangeManagementServiceImpl(dataAccessService, msoInterface, schedulerRestInterface); } } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java new file mode 100644 index 00000000..ff4b34f5 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java @@ -0,0 +1,616 @@ +package org.onap.vid.services; + +// +//import com.google.common.collect.ImmutableList; +//import com.google.common.collect.ImmutableMap; +//import org.apache.commons.lang.RandomStringUtils; +//import org.apache.commons.lang3.RandomUtils; +//import org.apache.commons.lang3.builder.ReflectionToStringBuilder; +//import org.apache.commons.lang3.builder.ToStringStyle; +//import org.hibernate.SessionFactory; +//import org.onap.vid.exceptions.GenericUncheckedException; +//import org.onap.vid.exceptions.OperationNotAllowedException; +//import org.onap.vid.job.Job; +//import org.onap.vid.job.JobAdapter; +//import org.onap.vid.job.JobType; +//import org.onap.vid.job.JobsBrokerService; +//import org.onap.vid.job.impl.JobDaoImpl; +//import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; +//import org.onap.vid.utils.DaoUtils; +//import org.onap.vid.config.DataSourceConfig; +//import org.onap.vid.config.JobAdapterConfig; +//import org.onap.portalsdk.core.domain.support.DomainVo; +//import org.onap.portalsdk.core.service.DataAccessService; +//import org.onap.portalsdk.core.util.SystemProperties; +//import org.springframework.test.context.ContextConfiguration; +//import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +//import org.testng.Assert; +//import org.testng.annotations.AfterMethod; +//import org.testng.annotations.BeforeMethod; +//import org.testng.annotations.DataProvider; +//import org.testng.annotations.Test; +// +//import javax.inject.Inject; +//import java.lang.reflect.Method; +//import java.time.LocalDateTime; +//import java.time.ZoneId; +//import java.util.*; +//import java.util.concurrent.*; +//import java.util.stream.Collectors; +//import java.util.stream.IntStream; +//import java.util.stream.Stream; +// +//import static java.util.concurrent.TimeUnit.MILLISECONDS; +//import static org.hamcrest.CoreMatchers.equalTo; +//import static org.hamcrest.CoreMatchers.is; +//import static org.hamcrest.MatcherAssert.assertThat; +//import static org.hamcrest.Matchers.both; +//import static org.hamcrest.Matchers.containsInAnyOrder; +//import static org.onap.vid.job.Job.JobStatus.*; +//import static org.onap.vid.utils.Streams.not; +//import static org.testng.Assert.assertNotNull; +//import static org.testng.AssertJUnit.assertEquals; +// +//@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, JobAdapterConfig.class}) +//public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { +// +// private static final int JOBS_COUNT = 127; +// private static final boolean DELETED = true; +// private final ExecutorService executor = Executors.newFixedThreadPool(90); +// +// private final Set<Long> threadsIds = new ConcurrentSkipListSet<>(); +// +// private final long FEW = 500; +// +// private final String JOBS_SHOULD_MATCH = "the jobs that added and those that pulled must be the same"; +// private final String JOBS_PEEKED_SHOULD_MATCH = "the jobs that added and those that peeked must be the same"; +// private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE = "Service status does not allow deletion from the queue"; +// private static final String DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE = "Service does not exist"; +// private JobsBrokerService broker; +// +// @Inject +// JobAdapter jobAdapter; +// @Inject +// private DataAccessService dataAccessService; +// @Inject +// private SessionFactory sessionFactory; +// +// /* +// - pulling jobs is limited to inserted ones +// - putting back allows getting the job again +// - multi threads safety +// - any added job should be visible with view +// +// - edges: +// - pulling with empty repo should return empty optional +// - pulling more than expected should return empty optional +// - putting one, over-pulling from a different thread +// - take before inserting, then insert while waiting +// +// */ +// +// private class NoJobException extends RuntimeException { +// } +// +// private Future<Job> newJobAsync(JobsBrokerService b) { +// return newJobAsync(b, createMockJob("user id")); +// } +// +// private Future<Job> newJobAsync(JobsBrokerService b, Job.JobStatus status) { +// return newJobAsync(b, createMockJob("user id", status)); +// } +// +// private Job createMockJob(String userId) { +// return jobAdapter.createJob( +// JobType.NoOp, +// new JobAdapter.AsyncJobRequest() { +// public int nothing = 42; +// }, +// UUID.randomUUID(), +// userId, +// RandomUtils.nextInt()); +// } +// +// private Job createMockJob(String userId, Job.JobStatus jobStatus) { +// Job job = createMockJob(userId); +// job.setStatus(jobStatus); +// return job; +// } +// +// private Future<Job> newJobAsync(JobsBrokerService b, Job job) { +// final Future<Job> jobFuture = executor.submit(() -> { +// accountThreadId(); +// +// b.add(job); +// +// return job; +// }); +// return jobFuture; +// } +// +// private void pushBackJobAsync(JobsBrokerService b, Job job) { +// executor.submit(() -> { +// accountThreadId(); +// b.pushBack(job); +// return job; +// }); +// } +// +// private Future<Optional<Job>> pullJobAsync(JobsBrokerService broker) { +// final Future<Optional<Job>> job = executor.submit(() -> { +// accountThreadId(); +// // Pull only pending jobs, as H2 database does not support our SQL for in-progress jobs +// return broker.pull(Job.JobStatus.PENDING, UUID.randomUUID().toString()); +// }); +// return job; +// } +// +// private Job waitForFutureOptionalJob(Future<Optional<Job>> retrievedOptionalJobFuture) { +// try { +// return retrievedOptionalJobFuture.get(FEW, MILLISECONDS).orElseThrow(NoJobException::new); +// } catch (TimeoutException | InterruptedException | ExecutionException e) { +// throw new RuntimeException(e); +// } +// } +// +// private Job waitForFutureJob(Future<Job> retrievedJobFuture) { +// try { +// return retrievedJobFuture.get(FEW, MILLISECONDS); +// } catch (TimeoutException | InterruptedException | ExecutionException e) { +// throw new RuntimeException(e); +// } +// } +// +// private List<Job> putAndGetALotOfJobs(JobsBrokerService broker) { +// final List<Job> originalJobs = putALotOfJobs(broker); +// final List<Job> retrievedJobs = getAlotOfJobs(broker); +// +// assertThat(JOBS_SHOULD_MATCH, retrievedJobs, containsInAnyOrder(originalJobs.toArray())); +// +// return retrievedJobs; +// } +// +// private List<Job> putALotOfJobs(JobsBrokerService broker) { +// int n = JOBS_COUNT; +// return IntStream.range(0, n) +// .mapToObj(i -> newJobAsync(broker)) +// .map(this::waitForFutureJob) +// .collect(Collectors.toList()); +// } +// +// private List<Job> getAlotOfJobs(JobsBrokerService broker) { +// int n = JOBS_COUNT; +// return IntStream.range(0, n) +// .mapToObj(i -> pullJobAsync(broker)) +// .map(this::waitForFutureOptionalJob) +// .collect(Collectors.toList()); +// } +// +// private void pushBackJobs(List<Job> jobs, JobsBrokerService broker) { +// jobs.forEach(job -> pushBackJobAsync(broker, job)); +// } +// +// private void accountThreadId() { +// threadsIds.add(Thread.currentThread().getId()); +// } +// +// @AfterMethod +// public void threadsCounter() { +// System.out.println("participating threads count: " + threadsIds.size()); +// threadsIds.clear(); +// } +// +// @BeforeMethod +// public void initializeBroker() { +// broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0); +// ((JobsBrokerServiceInDatabaseImpl) broker).deleteAll(); +// } +// +// @Test +// public void givenSingleJob_getIt_verifySameJob() { +// final Job originalJob = waitForFutureJob(newJobAsync(broker)); +// +// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); +// assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(originalJob)); +// } +// +// @Test +// public void givenManyJobs_getJobsAndPushThemBack_alwaysSeeAllOfThemWithPeek() throws InterruptedException { +// final List<Job> originalJobs = putALotOfJobs(broker); +// +// MILLISECONDS.sleep(FEW); +// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); +// +// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); +// +// MILLISECONDS.sleep(FEW); +// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); +// +// pushBackJobAsync(broker, retrievedJob); +// +// MILLISECONDS.sleep(FEW); +// assertThat(JOBS_PEEKED_SHOULD_MATCH, broker.peek(), containsInAnyOrder(originalJobs.toArray())); +// } +// +// @Test +// public void givenManyJobs_getThemAll_verifySameJobs() { +// putAndGetALotOfJobs(broker); +// } +// +// @Test +// public void givenManyJobs_getThemAllThenPushBackandGet_verifySameJobs() { +// final List<Job> retrievedJobs1 = putAndGetALotOfJobs(broker); +// +// pushBackJobs(retrievedJobs1, broker); +// final List<Job> retrievedJobs2 = getAlotOfJobs(broker); +// +// assertThat(JOBS_SHOULD_MATCH, retrievedJobs2, containsInAnyOrder(retrievedJobs1.toArray())); +// } +// +// private static Date toDate(LocalDateTime localDateTime) { +// return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); +// } +// +// private void setModifiedDateToJob(UUID jobUuid, Date date) { +// DomainVo job = dataAccessService.getDomainObject(JobDaoImpl.class, jobUuid, DaoUtils.getPropsMap()); +// job.setModified(date); +// DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { +// session.saveOrUpdate(job); +// return 1; +// }); +// } +// +// +// public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date) { +// return createNewJob(indexInBulk, templateId, userId, status, takenBy, date, false); +// } +// +// public static JobDaoImpl createNewJob(Integer indexInBulk, UUID templateId, String userId, Job.JobStatus status, String takenBy, LocalDateTime date, boolean deleted){ +// JobDaoImpl job = new JobDaoImpl(); +// job.setTypeAndData(JobType.NoOp, ImmutableMap.of("x", RandomStringUtils.randomAlphanumeric(15))); +// job.setIndexInBulk(indexInBulk); +// job.setTemplateId(templateId); +// job.setType(JobType.NoOp); +// job.setStatus(status); +// job.setTakenBy(takenBy); +// job.setCreated(toDate(date)); +// job.setModified(toDate(date)); +// job.setUserId(userId); +// if (deleted) { +// job.setDeletedAt(new Date()); +// } +// return job; +// } +// +// @DataProvider +// public static Object[][] jobs(Method test) { +// LocalDateTime oldestDate = LocalDateTime.now().minusHours(30); +// UUID sameTemplate = UUID.randomUUID(); +// return new Object[][]{ +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, oldestDate), +// createNewJob(22, UUID.randomUUID(), "userId", PENDING, null, oldestDate), +// createNewJob(11, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)), +// createNewJob(44, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(5))), +// 4, +// 0, +// PENDING, +// "Broker should pull the first pending job by oldest date then by job index" +// }, +// { ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", COMPLETED,null, oldestDate), +// createNewJob(11, UUID.randomUUID(), "userId", PENDING,null, oldestDate, DELETED),createNewJob(12, UUID.randomUUID(), "userId", FAILED,null, oldestDate), +// createNewJob(13, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate), +// createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate), +// createNewJob(22, UUID.randomUUID(), "userId", PENDING,null, oldestDate), +// createNewJob(33, UUID.randomUUID(), "userId", PENDING,null, LocalDateTime.now().minusHours(2))), +// 6, +// 5, +// PENDING, +// "Broker should pull the only pending - first pending job by oldest job - ignore deleted,completed, failed, in-progress and stopped statuses" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), +// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), +// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), +// 2, +// -1, +// PENDING, +// "Broker should not pull any job when it exceeded mso limit with count (in-progress) statuses" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), +// createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate), +// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), +// 2, +// -1, +// PENDING, +// "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), +// createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate), +// createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2))), +// 3, +// 2, +// PENDING, +// "Broker should pull first job when it doesn't exceeded mso limit with count(in-progress or pending && taken) statuses" +// }, +// {ImmutableList.of( +// createNewJob(11, sameTemplate, "userId", PENDING, UUID.randomUUID().toString(), oldestDate), +// createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate), +// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), +// 3, +// -1, +// PENDING, +// "Broker should not pull any job when there is another job from this template that was taken" +// }, +// {ImmutableList.of( +// createNewJob(11, sameTemplate, "userId", IN_PROGRESS, null, oldestDate), +// createNewJob(22, sameTemplate, "userId", PENDING, null, oldestDate), +// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), +// 3, +// -1, +// PENDING, +// "Broker should not pull any job when there is another job from this template that in progress" +// }, +// {ImmutableList.of( +// createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate), +// createNewJob(22, sameTemplate, "userId", STOPPED, null, oldestDate), +// createNewJob(33, sameTemplate, "userId", PENDING, null, LocalDateTime.now().minusHours(2))), +// 3, +// -1, +// PENDING, +// "Broker should not pull any job when there is another job from this template that was failed" +// }, +// {ImmutableList.of( +// createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate, DELETED), +// createNewJob(22, sameTemplate, "userId", STOPPED,null, oldestDate), +// createNewJob(33, sameTemplate, "userId", PENDING,null, LocalDateTime.now().minusHours(2))), +// 3, +// 2, +// PENDING, +// "Broker should pull pending job when there is another job from this template that was deleted, although failed" +// }, +// { ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, null, oldestDate), +// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate), +// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))), +// 3, +// 2, +// PENDING, +// "Broker should prioritize jobs of user that has no in-progress jobs" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userA", PENDING, UUID.randomUUID().toString(), oldestDate), +// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, oldestDate), +// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, LocalDateTime.now().minusHours(2))), +// 3, +// 2, +// PENDING, +// "Broker should prioritize jobs of user that has no taken jobs" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), +// createNewJob(22, UUID.randomUUID(), "userA", PENDING, null, LocalDateTime.now().minusHours(2)), +// createNewJob(31, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), +// createNewJob(32, UUID.randomUUID(), "userB", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), +// createNewJob(33, UUID.randomUUID(), "userB", PENDING, null, oldestDate)), +// 5, +// 4, +// PENDING, +// "Broker should take oldest job when there is one in-progress job to each user" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate), +// createNewJob(22, UUID.randomUUID(), UUID.randomUUID().toString(), IN_PROGRESS, null, oldestDate), +// createNewJob(33, UUID.randomUUID(), UUID.randomUUID().toString(), PENDING, null, LocalDateTime.now().minusHours(2))), +// 2, +// -1, +// PENDING, +// "Broker should not pull any job when it exceeded mso limit with count(in-progress or pending && taken) statuses" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), +// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, oldestDate), +// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), +// createNewJob(44, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(5))), +// 20, +// 1, +// IN_PROGRESS, +// "Broker with in progress topic should pull the first in progress and not taken job by oldest date" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate), +// createNewJob(12, UUID.randomUUID(), "userId", FAILED, null, oldestDate), +// createNewJob(13, UUID.randomUUID(), "userId", PENDING,null, oldestDate), +// createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate), +// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate, DELETED),createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS,null, oldestDate), +// createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS,null, LocalDateTime.now().minusHours(2))), +// 20, +// 5, +// IN_PROGRESS, +// "Broker with in progress topic should pull only in-progress jobs - first in-progress job by oldest date - ignore deleted,completed, failed, pending and stopped statuses" +// }, +// {ImmutableList.of( +// createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now()), +// createNewJob(22, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1)), +// createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(2))), +// 20, +// -1, +// IN_PROGRESS, +// "Broker with in progress topic should not pull any job if its modified date is smaller than now-interval (20 seconds)" +// } +// +// }; +// } +// +// +// @Test(dataProvider = "jobs") +// public void givenSomeJobs_pullNextJob_returnNextOrNothingAsExpected(List<JobDaoImpl> jobs, int msoLimit, int expectedIndexSelected, Job.JobStatus topic, String assertionReason) { +// JobsBrokerServiceInDatabaseImpl broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20); +// for (JobDaoImpl job : jobs) { +// Date modifiedDate = job.getModified(); +// broker.add(job); +// setModifiedDateToJob(job.getUuid(), modifiedDate); +// } +// Optional<Job> nextJob = broker.pull(topic, UUID.randomUUID().toString()); +// boolean shouldAnyBeSelected = expectedIndexSelected >= 0; +// Assert.assertEquals(nextJob.isPresent(), shouldAnyBeSelected, assertionReason); +// if (shouldAnyBeSelected) { +// Assert.assertEquals(jobs.get(expectedIndexSelected), nextJob.get(), assertionReason); +// } +// } +// +// @DataProvider +// public Object[][] topics() { +// return Arrays.stream(Job.JobStatus.values()) +// .filter(not(t -> ImmutableList.of(PENDING, IN_PROGRESS).contains(t))) +// .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{}); +// } +// +// @Test(dataProvider = "topics", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Unsupported topic.*") +// public void pullUnexpectedTopic_exceptionIsThrown(Job.JobStatus topic) { +// broker.pull(topic, UUID.randomUUID().toString()); +// } +// +// @Test(expectedExceptions = NoJobException.class) +// public void givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved() { +// Stream.of(Job.JobStatus.values()) +// .filter(not(s -> s.equals(PENDING))) +// .map(s -> createMockJob("some user id", s)) +// .map(job -> newJobAsync(broker, job)) +// .map(this::waitForFutureJob) +// .collect(Collectors.toList()); +// +// waitForFutureOptionalJob(pullJobAsync(broker)); +// } +// +// @Test +// public void givenPendingAndNonPendingJobs_getJobAsPendingTopic_verifyAJobRetrieved() { +// newJobAsync(broker); // this negated the expected result of the call below +// givenNonPendingJobs_getJobAsPendingTopic_verifyNothingRetrieved(); +// } +// +// @Test(expectedExceptions = NoJobException.class) +// public void givenManyJobs_pullThemAllAndAskOneMore_verifyFinallyNothingRetrieved() { +// putAndGetALotOfJobs(broker); +// waitForFutureOptionalJob(pullJobAsync(broker)); +// } +// +// @Test(expectedExceptions = NoJobException.class) +// public void givenNoJob_requestJob_verifyNothingRetrieved() throws InterruptedException, ExecutionException, TimeoutException { +// final Future<Optional<Job>> futureOptionalJob = pullJobAsync(broker); +// assertThat("job should not be waiting yet", futureOptionalJob.get(FEW, MILLISECONDS).isPresent(), is(false)); +// waitForFutureOptionalJob(futureOptionalJob); +// } +// +// @Test(expectedExceptions = IllegalStateException.class) +// public void givenSinglePulledJob_pushBackDifferentJob_verifyPushingRejected() { +// waitForFutureJob(newJobAsync(broker)); +// waitForFutureJob(newJobAsync(broker)); +// waitForFutureOptionalJob(pullJobAsync(broker)); +// +// Job myJob = createMockJob("user id"); +// myJob.setUuid(UUID.randomUUID()); +// +// broker.pushBack(myJob); //Should fail +// } +// +// @Test +// public void givenSingleJob_pushBackModifiedJob_verifyPulledIsVeryVeryTheSame() { +// final ImmutableMap<String, Object> randomDataForMostRecentJobType = +// ImmutableMap.of("42", 42, "complex", ImmutableList.of("a", "b", "c")); +// +// waitForFutureJob(newJobAsync(broker)); +// final Job job = waitForFutureOptionalJob(pullJobAsync(broker)); +// +// job.setStatus(Job.JobStatus.PENDING); +// job.setTypeAndData(JobType.NoOp, ImmutableMap.of("good", "morning")); +// job.setTypeAndData(JobType.HttpCall, ImmutableMap.of()); +// job.setTypeAndData(JobType.ServiceInstantiation, randomDataForMostRecentJobType); +// +// broker.pushBack(job); +// final Job retrievedJob = waitForFutureOptionalJob(pullJobAsync(broker)); +// +// assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(job)); +// assertThat(JOBS_SHOULD_MATCH, retrievedJob.getData(), both(equalTo(job.getData())).and(equalTo(randomDataForMostRecentJobType))); +// assertThat(JOBS_SHOULD_MATCH, jobDataReflected(retrievedJob), is(jobDataReflected(job))); +// } +// +// private static String jobDataReflected(Job job) { +// return new ReflectionToStringBuilder(job, ToStringStyle.SHORT_PREFIX_STYLE) +// .setExcludeFieldNames("created", "modified", "takenBy") +// .toString(); +// } +// +// @Test(expectedExceptions = IllegalStateException.class) +// public void givenSingleJob_pushBackTwice_verifyPushingRejected() { +// waitForFutureJob(newJobAsync(broker)); +// final Job job = waitForFutureOptionalJob(pullJobAsync(broker)); +// +// broker.pushBack(job); +// broker.pushBack(job); //Should fail +// } +// +// @Test +// public void addJob_PeekItById_verifySameJobWasPeeked() { +// String userId = UUID.randomUUID().toString(); +// Job myJob = createMockJob(userId); +// UUID uuid = broker.add(myJob); +// Job peekedJob = broker.peek(uuid); +// assertEquals("added testId is not the same as peeked TestsId", +// userId, +// peekedJob.getData().get("userId")); +// } +// +// @Test(dataProvider = "jobStatusesForSuccessDelete", expectedExceptions = NoJobException.class) +// public void givenOneJob_deleteIt_canPeekOnItButCantPull(Job.JobStatus status) { +// final Job job = waitForFutureJob(newJobAsync(broker, status)); +// broker.delete(job.getUuid()); +// assertNotNull(((JobDaoImpl) broker.peek(job.getUuid())).getDeletedAt(), "job should be deleted"); +// waitForFutureOptionalJob(pullJobAsync(broker)); +// } +// +// @DataProvider +// public static Object[][] jobStatusesForSuccessDelete() { +// return new Object[][]{ +// {PENDING}, +// {STOPPED} +// }; +// } +// +// @Test( +// dataProvider = "jobStatusesForFailedDelete", +// expectedExceptions = OperationNotAllowedException.class, +// expectedExceptionsMessageRegExp=DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE +// ) +// public void deleteJob_notAllowedStatus_exceptionIsThrown(Job.JobStatus status, boolean taken) { +// final Job job = waitForFutureJob(newJobAsync(broker, createMockJob("some user id", status))); +// +// if (taken) { +// waitForFutureOptionalJob(pullJobAsync(broker)); +// } +// +// +// broker.delete(job.getUuid()); +// } +// +// @DataProvider +// public static Object[][] jobStatusesForFailedDelete() { +// return new Object[][]{ +// {PENDING, true}, +// {IN_PROGRESS, false}, +// {COMPLETED, false}, +// {PAUSE, false}, +// {FAILED, false}, +// }; +// } +// +// @Test(expectedExceptions = OperationNotAllowedException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_NOT_EXIST_EXCEPTION_MESSAGE) +// public void deleteJob_notExist_exceptionIsThrown() { +// waitForFutureJob(newJobAsync(broker, createMockJob("some user id", PENDING))); +// broker.delete(new UUID(111, 111)); +// } +// +//} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java new file mode 100644 index 00000000..cb9eb93d --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java @@ -0,0 +1,283 @@ +package org.onap.vid.services; + +import com.google.common.collect.ImmutableList; +import org.codehaus.jackson.map.ObjectMapper; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.model.AaiGetPortMirroringSourcePorts; +import org.onap.vid.aai.model.PortDetailsTranslator; +import org.onap.vid.aai.model.RelatedTo; +import org.onap.vid.aai.model.SimpleResult; +import org.onap.vid.properties.Features; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.collection.IsEmptyCollection.empty; +import static org.mockito.Mockito.when; + +public class PortDetailsTranslatorTest { + + private static final ObjectMapper om = new ObjectMapper(); + + @InjectMocks + private PortDetailsTranslator portDetailsTranslator = new PortDetailsTranslator(); + + @Mock + private FeatureManager featureManager; + + @BeforeMethod + public void initMocks() throws Exception { + MockitoAnnotations.initMocks(this); + when(featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER)).thenReturn(true); + } + + @Test + public void extractPortDetailsFromProperties_givenValidAaiResponse() throws IOException { + + final String aaiResponse = "{\n" + + " \"results\": [\n" + + " {\n" + + " \"id\": \"4876980240\",\n" + + " \"node-type\": \"l-interface\",\n" + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"properties\": {\n" + + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + + " \"is-port-mirrored\": false,\n" + + " \"resource-version\": \"1519383879190\",\n" + + " \"in-maint\": false,\n" + + " \"is-ip-unnumbered\": false\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + + AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); + + + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(), aaiResponse); + + assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsOk.class))); + + PortDetailsTranslator.PortDetailsOk portDetailsOk = (PortDetailsTranslator.PortDetailsOk) portDetails; + assertThat(portDetailsOk.getInterfaceName(), is("zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib")); + assertThat(portDetailsOk.getInterfaceId(), is("6de7bf87-6faa-4984-9492-18d1188b3d4a")); + assertThat(portDetailsOk.getIsPortMirrored(), is(false)); + } + + @Test + public void extractPortDetailsFromProperties_givenAaiResponseWithInstanceNameNull_yieldException() throws IOException { + final String aaiResponse = "{\n" + + " \"results\": [\n" + + " {\n" + + " \"id\": \"4876980240\",\n" + + " \"node-type\": \"l-interface\",\n" + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"properties\": {\n" + + " \"interface-name\": null,\n" + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + + " \"is-port-mirrored\": false,\n" + + " \"resource-version\": \"1519383879190\",\n" + + " \"in-maint\": false,\n" + + " \"is-ip-unnumbered\": false\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + + AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + + assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); + + PortDetailsTranslator.PortDetailsError portDetailsError = (PortDetailsTranslator.PortDetailsError) portDetails; + assertThat(portDetailsError.getErrorDescription(), is("Value of 'interface-name' is missing.")); + assertThat(portDetailsError.getRawAaiResponse(), is(aaiResponse)); + } + + @Test + public void extractPortDetailsFromProperties_givenAaiResponseWithInstanceIdNull_yieldException() throws IOException { + final String aaiResponse = "{\n" + + " \"results\": [\n" + + " {\n" + + " \"id\": \"4876980240\",\n" + + " \"node-type\": \"l-interface\",\n" + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"properties\": {\n" + + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"interface-id\": null,\n" + + " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + + " \"is-port-mirrored\": false,\n" + + " \"resource-version\": \"1519383879190\",\n" + + " \"in-maint\": false,\n" + + " \"is-ip-unnumbered\": false\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + + AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + + assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); + + PortDetailsTranslator.PortDetailsError portDetailsError = (PortDetailsTranslator.PortDetailsError) portDetails; + assertThat(portDetailsError.getErrorDescription(), is("Value of 'interface-id' is missing.")); + assertThat(portDetailsError.getRawAaiResponse(), is(aaiResponse)); + } + + @Test + public void extractPortDetailsFromProperties_givenAaiResponseWithEmptyInstanceId_yieldException() throws IOException { + final String aaiResponse = "{\n" + + " \"results\": [\n" + + " {\n" + + " \"id\": \"4876980240\",\n" + + " \"node-type\": \"l-interface\",\n" + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"properties\": {\n" + + " \"interface-name\": \"\",\n" + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + + " \"is-port-mirrored\": false,\n" + + " \"resource-version\": \"1519383879190\",\n" + + " \"in-maint\": false,\n" + + " \"is-ip-unnumbered\": false\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + + AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + + assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); + + PortDetailsTranslator.PortDetailsError portDetailsError = (PortDetailsTranslator.PortDetailsError) portDetails; + assertThat(portDetailsError.getErrorDescription(), is("Value of 'interface-name' is empty.")); + assertThat(portDetailsError.getRawAaiResponse(), is(aaiResponse)); + } + + @Test + public void extractPortDetailsFromProperties_givenAaiResponseWithIsPortMirroredNull_yieldException() throws IOException { + final String aaiResponse = "{\n" + + " \"results\": [\n" + + " {\n" + + " \"id\": \"4876980240\",\n" + + " \"node-type\": \"l-interface\",\n" + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"properties\": {\n" + + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\",\n" + + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"interface-id\": \"6de7bf87-6faa-4984-9492-18d1188b3d4a\",\n" + + " \"macaddr\": \"02:6d:e7:bf:87:6f\",\n" + + " \"network-name\": \"APP-C-24595-D-T001-vprobe_int_pktmirror_net_1\",\n" + + " \"is-port-mirrored\": null,\n" + + " \"resource-version\": \"1519383879190\",\n" + + " \"in-maint\": false,\n" + + " \"is-ip-unnumbered\": false\n" + + " }\n" + + " }\n" + + " ]\n" + + "}"; + + AaiGetPortMirroringSourcePorts aaiGetPortMirroringSourcePorts = om.readValue(aaiResponse, AaiGetPortMirroringSourcePorts.class); + PortDetailsTranslator.PortDetails portDetails = PortDetailsTranslator.extractPortDetailsFromProperties(aaiGetPortMirroringSourcePorts.getResults().get(0).getProperties(),aaiResponse); + + assertThat(portDetails, is(instanceOf(PortDetailsTranslator.PortDetailsError.class))); + + PortDetailsTranslator.PortDetailsError portDetailsError = (PortDetailsTranslator.PortDetailsError) portDetails; + assertThat(portDetailsError.getErrorDescription(), is("Value of 'is-port-mirrored' is missing.")); + assertThat(portDetailsError.getRawAaiResponse(), is(aaiResponse)); + } + + @Test + public void getFilteredPortList_givenEmptyList_ReturnEmptyList() { + + final ImmutableList<SimpleResult> input = ImmutableList.of(); + + List<SimpleResult> result = portDetailsTranslator.getFilteredPortList(input); + assertThat("List size if different than expected", result, is(empty())); + } + + @DataProvider + public static Object[][] trueAndFalse() { + return new Object[][]{ + { Boolean.TRUE }, { Boolean.FALSE } + }; + } + + @Test(dataProvider = "trueAndFalse") + public void getFilteredPortList_givenFeatureFlagIsOff_returnAllLInterfaces(Boolean advancedPortsFilterFlag) throws IOException { + when(featureManager.isActive(Features.FLAG_ADVANCED_PORTS_FILTER)).thenReturn(advancedPortsFilterFlag); + + final String relationshipLabelSource = "org.onap.relationships.inventory.Source"; + final String nodeTypeLInterface = "l-interface"; + + SimpleResult lInterfaceWithSource = + buildSimpleResult(nodeTypeLInterface, relationshipLabelSource); + SimpleResult lInterfaceWithTwoSources = + buildSimpleResult(nodeTypeLInterface, relationshipLabelSource, relationshipLabelSource); + SimpleResult lInterfaceWithSourceAndMore = + buildSimpleResult(nodeTypeLInterface, relationshipLabelSource, "not a source"); + SimpleResult lInterfaceWithoutSource = + buildSimpleResult(nodeTypeLInterface, "not a source"); + SimpleResult lInterfaceWithoutRelations = + buildSimpleResult(nodeTypeLInterface); + SimpleResult fooTypeWithSource = + buildSimpleResult("not an l-interface", relationshipLabelSource); + SimpleResult fooTypeWithoutSource = + buildSimpleResult("not an l-interface", "not a source"); + + final ImmutableList<SimpleResult> input = ImmutableList.of( + fooTypeWithSource, fooTypeWithoutSource, + lInterfaceWithTwoSources, lInterfaceWithSourceAndMore, + lInterfaceWithoutSource, lInterfaceWithSource, + lInterfaceWithoutRelations); + + List<SimpleResult> result = portDetailsTranslator.getFilteredPortList(input); + + if (advancedPortsFilterFlag) { + assertThat("List should contain all l-interfaces with a related source", result, containsInAnyOrder( + lInterfaceWithSource, lInterfaceWithSourceAndMore, + lInterfaceWithTwoSources)); + } else { + assertThat("List should contain all l-interfaces", result, containsInAnyOrder( + lInterfaceWithSource, lInterfaceWithoutSource, + lInterfaceWithoutRelations, lInterfaceWithSourceAndMore, + lInterfaceWithTwoSources)); + } + } + + private SimpleResult buildSimpleResult(String nodeType, String... relationshipLabels) { + SimpleResult simpleResult = new SimpleResult(); + simpleResult.setNodeType(nodeType); + simpleResult.setRelatedTo(Stream.of(relationshipLabels).map(label -> + new RelatedTo("my foo id", label, "logical-link", "foo url")) + .collect(Collectors.toList()) + ); + return simpleResult; + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java new file mode 100644 index 00000000..7dbd622a --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java @@ -0,0 +1,122 @@ +package org.onap.vid.services; + +import com.google.common.collect.ImmutableMap; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.mockito.Answers; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.AsdcClient; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.asdc.parser.ToscaParserImpl2; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.properties.Features; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.Map; +import java.util.UUID; + +import static java.util.stream.Collectors.toMap; +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.*; + +public class VidServiceImplTest { + + @Mock(answer = Answers.RETURNS_MOCKS) + AsdcClient asdcClientMock; + + @Mock(answer = Answers.RETURNS_MOCKS) + ToscaParserImpl2 toscaParserMock; + + @Mock + FeatureManager featureManager; + + private final UUID uuid1 = UUID.randomUUID(); + private final UUID uuid2 = UUID.randomUUID(); + private final UUID uuid3 = UUID.randomUUID(); + private final Map<UUID, Service> pseudoServiceByUuid = ImmutableMap.of( + uuid1, mock(Service.class), + uuid2, mock(Service.class), + uuid3, mock(Service.class) + ); + + private final Map<Service, ServiceModel> pseudoModelByService = + pseudoServiceByUuid.values().stream() + .collect(toMap(service -> service, service -> mock(ServiceModel.class))); + private VidServiceImpl vidService; + + private ServiceModel expectedServiceModelForUuid(UUID uuid) { + final ServiceModel serviceModel = pseudoModelByService.get(pseudoServiceByUuid.get(uuid)); + assertThat(serviceModel, is(not(nullValue()))); + return serviceModel; + } + + @BeforeMethod + public void initMocks() throws AsdcCatalogException, SdcToscaParserException, IllegalAccessException { + MockitoAnnotations.initMocks(this); + + vidService = new VidServiceImpl(asdcClientMock, featureManager); + FieldUtils.writeField(vidService, "toscaParser", toscaParserMock, true); + + when(featureManager.isActive(Features.FLAG_SERVICE_MODEL_CACHE)).thenReturn(true); + + when(asdcClientMock.getService(any())).thenAnswer(invocation -> pseudoServiceByUuid.get(invocation.getArguments()[0])); + when(toscaParserMock.makeServiceModel(any(), any())).thenAnswer(invocation -> pseudoModelByService.get(invocation.getArguments()[1])); + } + + @Test + public void whenGetServiceMultipleTimes_asdcIsCalledOnlyOnce() throws AsdcCatalogException { + vidService.getService(uuid1.toString()); + vidService.getService(uuid1.toString()); + vidService.getService(uuid1.toString()); + + verify(asdcClientMock, times(1)).getService(uuid1); + } + + @Test + public void whenGetServiceTwiceWithResetBetween_asdcIsCalledTwice() throws AsdcCatalogException { + vidService.getService(uuid1.toString()); + vidService.invalidateServiceCache(); + vidService.getService(uuid1.toString()); + + verify(asdcClientMock, times(2)).getService(uuid1); + } + + @Test + public void cache_saves_service_model_correctly() throws AsdcCatalogException { + ServiceModel service1 = vidService.getService(uuid1.toString()); + ServiceModel service2 = vidService.getService(uuid1.toString()); + ServiceModel service3 = vidService.getService(uuid1.toString()); + + assertThat(service1, sameInstance(expectedServiceModelForUuid(uuid1))); + assertThat(service1, sameInstance(service2)); + assertThat(service1, sameInstance(service3)); + } + + @Test + public void cache_provide_correct_serviceModel() throws AsdcCatalogException { + ServiceModel service2 = vidService.getService(uuid2.toString()); + assertThat(service2, sameInstance(expectedServiceModelForUuid(uuid2))); + + ServiceModel service3 = vidService.getService(uuid3.toString()); + assertThat(service3, sameInstance(expectedServiceModelForUuid(uuid3))); + + UUID nonExisting = UUID.randomUUID(); + ServiceModel service4 = vidService.getService(nonExisting.toString()); + assertThat(service4, is(nullValue())); + } + + @Test(expectedExceptions = AsdcCatalogException.class, expectedExceptionsMessageRegExp = "someMessage") + public void whenAsdcClientThrowAsdcCatalogException_thenGetServiceAlsoThrowIt() throws AsdcCatalogException { + when(asdcClientMock.getServiceToscaModel(any())).thenThrow(new AsdcCatalogException("someMessage")); + vidService.getService(uuid1.toString()); + } + +} + diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java index 73a79cd2..175f87f2 100644 --- a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java +++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java @@ -1,12 +1,30 @@ package org.onap.vid.testUtils; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Assert; +import org.mockito.MockSettings; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.vid.asdc.beans.Service; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; import java.util.Iterator; +import java.util.List; import static fj.parser.Parser.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.*; /** * Created by Oren on 6/7/17. @@ -64,5 +82,81 @@ public class TestUtils { } } + public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException { + return readJsonResourceFileAsObject(pathInResource, valueType, false); + } + + public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType, boolean ignoreUnknownProperties) + throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, ignoreUnknownProperties); + return objectMapper.readValue( + TestUtils.class.getResource(pathInResource), + valueType); + } + + + public static class JavaxRsClientMocks { + private final javax.ws.rs.client.Client fakeClient; + private final javax.ws.rs.client.Invocation.Builder fakeBuilder; + private final Response fakeResponse; + + public javax.ws.rs.client.Client getFakeClient() { + return fakeClient; + } + + public javax.ws.rs.client.Invocation.Builder getFakeBuilder() { + return fakeBuilder; + } + + public Response getFakeResponse() { + return fakeResponse; + } + + public JavaxRsClientMocks() { + final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType()); + fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings); + fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings); + fakeResponse = mock(Response.class, mockSettings); + final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings); + + TriesToReturnMockByType.setAvailableMocks( + fakeClient, + fakeWebTarget, + fakeBuilder, + fakeResponse + ); + + Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null); + Mockito.when(fakeBuilder.get(eq(InputStream.class))).thenReturn(new ByteArrayInputStream(new byte[]{})); + Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null); + + Mockito.when(fakeResponse.getStatus()).thenReturn(200); + Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null); + } + } + + /* + inspired out from newer Mockito version + returns a mock from given list if it's a matching return-type + */ + private static class TriesToReturnMockByType implements Answer<Object>, Serializable { + private final Answer<Object> defaultReturn = RETURNS_DEFAULTS; + private static List<Object> availableMocks = ImmutableList.of(); + + static void setAvailableMocks(Object... mocks) { + availableMocks = ImmutableList.copyOf(mocks); + } + + public Object answer(InvocationOnMock invocation) throws Throwable { + Class<?> methodReturnType = invocation.getMethod().getReturnType(); + + return availableMocks.stream() + .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass())) + //.peek(m -> System.out.println("found a mock: " + m.getClass().getName())) + .findFirst() + .orElse(defaultReturn.answer(invocation)); + } + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java new file mode 100644 index 00000000..7bc3fca1 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/utils/LoggingUtilsTest.java @@ -0,0 +1,99 @@ +package org.onap.vid.utils; + +import com.fasterxml.jackson.databind.JsonMappingException; +import org.codehaus.jackson.JsonLocation; +import org.codehaus.jackson.JsonParseException; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import sun.security.provider.certpath.SunCertPathBuilderException; +import sun.security.validator.ValidatorException; + +import javax.crypto.BadPaddingException; +import javax.net.ssl.SSLHandshakeException; +import javax.ws.rs.ProcessingException; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.onap.vid.testUtils.RegExMatcher.matchesRegEx; + +public class LoggingUtilsTest { + + @DataProvider + public static Object[][] exceptions() { + Exception e0 = new CertificateException("No X509TrustManager implementation available"); + Exception noTrustMngrImplException = new SSLHandshakeException(e0.toString()); + noTrustMngrImplException.initCause(e0); + + Exception e1 = new BadPaddingException("Given final block not properly padded"); + Exception incorrectPasswordException = new IOException("keystore password was incorrect", + new UnrecoverableKeyException("failed to decrypt safe contents entry: " + e1)); + String incorrectPasswordExceptionDescription = "" + + "java.io.IOException: keystore password was incorrect: " + + "java.security.UnrecoverableKeyException: failed to decrypt safe contents entry: " + + "javax.crypto.BadPaddingException: Given final block not properly padded"; + + Exception e2 = new SunCertPathBuilderException("unable to find valid certification path to requested target"); + Exception noValidCert = new ProcessingException(new ValidatorException("PKIX path building failed: " + e2.toString(), e2)); + String noValidCertDescription = "" + + "javax.ws.rs.ProcessingException: " + + "sun.security.validator.ValidatorException: PKIX path building failed: " + + "sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target"; + + RuntimeException codehausParseException = new RuntimeException(new JsonParseException("Unexpected character ('<' (code 60)):" + + " expected a valid value (number, String, array, object, 'true', 'false' or 'null')", + new JsonLocation("<html>i'm an error</html>", 25, 1, 1))); + String codehausParseDescription = "" + + "org.codehaus.jackson.JsonParseException: Unexpected character ('<' (code 60)):" + + " expected a valid value (number, String, array, object, 'true', 'false' or 'null')\n" + + " at [Source: <html>i'm an error</html>; line: 1, column: 1]"; + + RuntimeException fasterxmlMappingException = new RuntimeException(new JsonMappingException("Can not deserialize instance of java.lang.String out of START_ARRAY token", + new com.fasterxml.jackson.core.JsonLocation("{ example json }", 15, 1, 20))); + String fasterxmlMappingDescription = "" + + "com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_ARRAY token\n" + + " at [Source: { example json }; line: 1, column: 20]"; + + return new Object[][]{ + {"javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No X509TrustManager implementation available", + noTrustMngrImplException}, + {"java.lang.StringIndexOutOfBoundsException: String index out of range: 4", + new StringIndexOutOfBoundsException(4)}, + {"java.io.FileNotFoundException: vid/WEB-INF/cert/aai-client-cert.p12", + new FileNotFoundException("vid/WEB-INF/cert/aai-client-cert.p12")}, + {"NullPointerException at LoggingUtilsTest.java:[0-9]+", + new NullPointerException("null")}, + {incorrectPasswordExceptionDescription, + incorrectPasswordException}, + {incorrectPasswordExceptionDescription, + new GenericUncheckedException(incorrectPasswordException)}, + {"javax.ws.rs.ProcessingException: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_expired", + new ProcessingException(new SSLHandshakeException("Received fatal alert: certificate_expired"))}, + {noValidCertDescription, + noValidCert}, + {escapeBrackets(codehausParseDescription), + codehausParseException}, + {escapeBrackets(fasterxmlMappingDescription), + fasterxmlMappingException}, + {"org.onap.vid.exceptions.GenericUncheckedException: top message: org.onap.vid.exceptions.GenericUncheckedException: root message", + new GenericUncheckedException("top message", new IOException("sandwich message", new GenericUncheckedException("root message")))}, + {"org.onap.vid.exceptions.GenericUncheckedException: basa", + new GenericUncheckedException("basa")} + }; + + } + + @Test(dataProvider = "exceptions") + public void testExceptionToDescription(String expectedDescription, Exception exceptionToDescribe) { + String expectedButDotsEscaped = expectedDescription.replace(".", "\\."); + + assertThat(Logging.exceptionToDescription(exceptionToDescribe), matchesRegEx(expectedButDotsEscaped)); + } + + private static String escapeBrackets(String in) { + return in.replaceAll("[\\(\\[\\{\\)]", "\\\\$0"); + } +}
\ No newline at end of file |