From 6ad41e3ccd398a2721f41ad61c80b7bb03f7d127 Mon Sep 17 00:00:00 2001 From: Ittay Stern Date: Mon, 31 Dec 2018 17:21:27 +0200 Subject: Merge from ECOMP's repository Main Features -------------- - Async-Instantiation jobs mechanism major update; still WIP (package `org.onap.vid.job`) - New features in View/Edit: Activate fabric configuration; show related networks; soft delete - Support AAI service-tree traversal (`AAIServiceTree`) - In-memory cache for SDC models and certain A&AI queries (`CacheProviderWithLoadingCache`) - Upgrade TOSCA Parser and add parsing options; fix malformed TOSCA models - Resolve Cloud-Owner values for MSO - Pass X-ONAP headers to MSO Infrastructure -------------- - Remove codehaus' jackson mapper; use soley fasterxml 2.9.7 - Surefire invokes both TestNG and JUnit tests - Support Kotlin source files - AaiController2 which handles errors in a "Spring manner" - Inline generated-sources and remove jsonschema2pojo Quality -------- - Cumulative bug fixes (A&AI API, UI timeouts, and many more) - Many Sonar issues cleaned-up - Some unused classes removed - Minor changes in vid-automation project, allowing some API verification to run Hard Merges ------------ - HTTP Clients (MSO, A&AI, WebConfig, OutgoingRequestHeadersTest) - Moved `package org.onap.vid.controllers` to `controller`, without plural -- just to keep semantic sync with ECOMP. Reference commit in ECOMP: 3d1141625 Issue-ID: VID-378 Change-Id: I9c8d1e74caa41815891d441fc0760bb5f29c5788 Signed-off-by: Ittay Stern --- .../test/java/org/onap/vid/aai/AaiClientTest.java | 531 ++++++++++++++++----- .../onap/vid/aai/AaiOverTLSClientServerTest.java | 72 +-- .../org/onap/vid/aai/AaiOverTLSClientTest.java | 12 +- .../onap/vid/aai/OperationalEnvironmentTest.java | 18 +- .../test/java/org/onap/vid/aai/VnfResultTest.java | 5 +- .../onap/vid/aai/model/AaiGetPnfResponseTest.java | 10 +- .../org/onap/vid/aai/model/PnfPropertiesTest.java | 4 +- .../java/org/onap/vid/aai/model/PnfResultTest.java | 6 +- .../org/onap/vid/aai/util/CacheConfigTest.java | 32 ++ .../org/onap/vid/aai/util/CacheProviderTest.java | 41 ++ .../util/CacheProviderWithLoadingCacheTest.java | 313 ++++++++++++ .../org/onap/vid/aai/util/HttpsAuthClientTest.java | 41 +- .../onap/vid/aai/util/NonCachingCacheProvider.java | 14 + .../aai/util/ServiceInstanceStandardQueryTest.java | 405 ++++++++++++++++ .../vid/aai/util/SingleAAIRestInterfaceTest.java | 75 +-- 15 files changed, 1321 insertions(+), 258 deletions(-) create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java (limited to 'vid-app-common/src/test/java/org/onap/vid/aai') 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 201ec0981..2656532f4 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,26 +1,6 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2018 Nokia. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - package org.onap.vid.aai; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; @@ -28,18 +8,15 @@ 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.apache.http.HttpStatus; import org.mockito.Mockito; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelatedToProperty; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; -import org.onap.vid.aai.model.AaiNodeQueryResponse; -import org.onap.vid.aai.model.PortDetailsTranslator; -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.aai.util.ServletRequestHelper; -import org.onap.vid.aai.util.SystemPropertyHelper; -import org.onap.vid.controllers.LocalWebConfig; +import org.onap.vid.aai.model.*; +import org.onap.vid.aai.util.*; +import org.onap.vid.controller.LocalWebConfig; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.Subscriber; import org.onap.vid.model.SubscriberList; @@ -47,6 +24,7 @@ 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.testUtils.TestUtils; +import org.onap.vid.utils.Unchecked; import org.springframework.http.HttpMethod; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.web.WebAppConfiguration; @@ -65,42 +43,53 @@ import javax.ws.rs.client.Client; import javax.ws.rs.core.Response; import java.io.FileNotFoundException; import java.io.IOException; +import java.net.URI; import java.security.cert.CertificateException; import java.util.ArrayList; +import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; -import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.*; +import static org.hamcrest.Matchers.*; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isNull; import static org.mockito.Mockito.*; +import static org.onap.vid.utils.Unchecked.toURI; import static org.testng.Assert.*; @ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) @WebAppConfiguration public class AaiClientTest { + private final String NO_LCP_REGION_AND_TENANTS_MSG = "A&AI has no LCP Region & Tenants associated to subscriber 'subscriberId' and service type 'serviceType'"; private AaiClient aaiClientMock; private ServletContext servletContext; @BeforeMethod - public void initMocks() { + public void initMocks(){ aaiClientMock = mock(AaiClient.class); aaiClientMock.logger = mock(EELFLoggerDelegate.class); + aaiClientMock.objectMapper = new ObjectMapper(); servletContext = mock(ServletContext.class); when(servletContext.getRealPath(any(String.class))).thenReturn(""); - when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(null); + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(null); + when(aaiClientMock.doAaiGet(any(URI.class), anyBoolean(), anyBoolean())).thenReturn(null); } @DataProvider public static Object[][] logicalLinkData() { - return new Object[][]{ + return new Object[][] { {"", "network/logical-links/logical-link/"}, {"link", "network/logical-links/logical-link/link"} }; @@ -111,26 +100,21 @@ public class AaiClientTest { when(aaiClientMock.getLogicalLink(any(String.class))).thenCallRealMethod(); aaiClientMock.getLogicalLink(link); - Mockito.verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)), any(Boolean.class)); + verify(aaiClientMock).doAaiGet(argThat(s -> equalsIgnoreCase(s, expectedUrl)),any(Boolean.class)); } @DataProvider public static Object[][] subscribersResults() { - return new Object[][]{ - {new SubscriberList(new ArrayList() {{ - add(new Subscriber()); - add(new Subscriber()); - }}), true}, - {new SubscriberList(new ArrayList() {{ - add(new Subscriber()); - }}), true}, + return new Object[][] { + {new SubscriberList(new ArrayList() {{ add(new Subscriber()); add(new Subscriber()); }}), true}, + {new SubscriberList(new ArrayList() {{ add(new Subscriber()); }}), true}, {new SubscriberList(new ArrayList()), false} }; } @Test(dataProvider = "subscribersResults") - public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable) { - ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, new HttpRequestMetadata( + public void testProbeAaiGetAllSubscribers_returnsTwoToZeroSubscribers_ResultsAsExpected(SubscriberList subscribers, boolean isAvailable){ + ExternalComponentStatus expectedStatus = new ExternalComponentStatus(ExternalComponentStatus.Component.AAI,isAvailable, new HttpRequestMetadata( HttpMethod.GET, 200, "url", @@ -143,9 +127,79 @@ public class AaiClientTest { 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()))); + ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); + assertThat(statusDataReflected(result),is(statusDataReflected(expectedStatus))); + assertThat(requestMetadataReflected(result.getMetadata()),is(requestMetadataReflected(expectedStatus.getMetadata()))); + } + + @Test(expectedExceptions = Exception.class) + public void typedAaiGet_aaiRestInterfaceRestGetReturnsError_exceptionIsThrown() { + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR, "entity"); + mockForGetRequest(aaiRestInterface, responseWithRequestInfo); + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + try { + + aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class); + + } catch (Exception e) { + assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class)); + ExceptionWithRequestInfo e2 = ((ExceptionWithRequestInfo) e); + assertThat(e2.getHttpCode(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + assertThat(e2.getRawData(), is("entity")); + assertThat(e2.getHttpMethod(), is(HttpMethod.GET)); + assertThat(e2.getRequestedUrl(), is("/my/mocked/url")); + + throw e; + } + } + + @Test(expectedExceptions = Exception.class) + public void typedAaiGet_aaiRestInterfaceRestGetReturnsInparsableResponse_exceptionIsThrown() { + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "entity"); + mockForGetRequest(aaiRestInterface, responseWithRequestInfo); + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + try { + + aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class); + + } catch (Exception e) { + assertThat(ExceptionUtils.getStackTrace(e), e, instanceOf(ExceptionWithRequestInfo.class)); + assertThat(e.getCause(), + hasProperty("cause", is(instanceOf(com.fasterxml.jackson.core.JsonParseException.class))) + ); + throw e; + } + } + + @Test + public void typedAaiGet_aaiRestInterfaceRestGetReturns_objectIsFine() { + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, + "{ \"property-key\": \"foo\", \"property-value\": \"bar\" }"); + mockForGetRequest(aaiRestInterface, responseWithRequestInfo); + + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + final RelatedToProperty relatedToPropertyAaiResponse = aaiClient.typedAaiGet(toURI("/irrelevant/url"), RelatedToProperty.class); + + assertThat(relatedToPropertyAaiResponse.getPropertyKey(), is("foo")); + assertThat(relatedToPropertyAaiResponse.getPropertyValue(), is("bar")); + } + + private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) { + return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET); + } + + private ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity, String requestUrl, HttpMethod method) { + final Response mockResponse = mock(Response.class); + when(mockResponse.getStatus()).thenReturn(status.getStatusCode()); + when(mockResponse.getStatusInfo()).thenReturn(status); + when(mockResponse.readEntity(String.class)).thenReturn(entity); + return new ResponseWithRequestInfo(mockResponse, requestUrl, method); } //serialize fields except of fields we cannot know ahead of time @@ -164,12 +218,12 @@ public class AaiClientTest { @DataProvider public static Object[][] rawData() { return new Object[][]{ - {"errorMessage",}, {""}, {null} + {"errorMessage", }, {""}, {null} }; } @Test(dataProvider = "rawData") - public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData) { + public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String rawData){ Mockito.when(aaiClientMock.getAllSubscribers(true)).thenReturn( new AaiResponseWithRequestInfo<>(HttpMethod.GET, "url", null, rawData)); @@ -180,7 +234,7 @@ public class AaiClientTest { @DataProvider public static Object[][] exceptions() { - return new Object[][]{ + return new Object[][] { {"NullPointerException", "errorMessage", new ExceptionWithRequestInfo(HttpMethod.GET, "url", "errorMessage", null, new NullPointerException())}, @@ -193,7 +247,7 @@ public class AaiClientTest { } @Test(dataProvider = "exceptions") - public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception) { + public void testProbeAaiGetFullSubscribersWithNullResponse_returnsNotAvailableWithErrorRawData(String description, String expectedRawData, Exception exception){ Mockito.when(aaiClientMock.getAllSubscribers(true)).thenThrow(exception); ExternalComponentStatus result = callProbeAaiGetAllSubscribersAndAssertNotAvailable(); if (exception instanceof ExceptionWithRequestInfo) { @@ -205,7 +259,7 @@ public class AaiClientTest { private ExternalComponentStatus callProbeAaiGetAllSubscribersAndAssertNotAvailable() { Mockito.when(aaiClientMock.probeAaiGetAllSubscribers()).thenCallRealMethod(); - ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); + ExternalComponentStatus result = aaiClientMock.probeAaiGetAllSubscribers(); assertFalse(result.isAvailable()); return result; } @@ -226,56 +280,55 @@ public class AaiClientTest { assertEquals(response.getErrorMessage(), "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}"); } - @Test + @Test(expectedExceptions = AaiClient.ParsingGetTenantsResponseFailure.class, expectedExceptionsMessageRegExp = NO_LCP_REGION_AND_TENANTS_MSG) public void getTenants_Arguments_Are_Valid_But_Tenants_Not_Exist() { - when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod(); + when(aaiClientMock.getTenantsNonCached(any(String.class),any(String.class))).thenCallRealMethod(); Response generalEmptyResponse = mock(Response.class); - when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(generalEmptyResponse); + 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'\"}"); + aaiClientMock.getTenantsNonCached("subscriberId", "serviceType"); + } + @Test + public void whenCacheThrowException_thenGetTenantReturnAaiResponse() { + CacheProvider mockCacheProvider = mock(CacheProvider.class); + CacheProvider.Cache mockCache = mock(CacheProvider.Cache.class); + AaiClient aaiClientUnderTest = new AaiClient(null, null, mockCacheProvider); + + when(mockCacheProvider.aaiClientCacheFor(any(), any())).thenReturn(mockCache); + when(mockCache.get(any())).thenThrow(new AaiClient.ParsingGetTenantsResponseFailure(NO_LCP_REGION_AND_TENANTS_MSG)); + AaiResponse aaiResponse = aaiClientUnderTest.getTenants("subscriberId", "serviceType"); + assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, aaiResponse.getHttpCode()); + assertEquals("{\"statusText\":\""+NO_LCP_REGION_AND_TENANTS_MSG+"\"}", aaiResponse.getErrorMessage()); } @Test public void getTenants_Arguments_Are_Valid_Get_The_Tenanats() { - when(aaiClientMock.getTenants(any(String.class), any(String.class))).thenCallRealMethod(); + when(aaiClientMock.getTenantsNonCached(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; - } + when(generalEmptyResponse.getStatusInfo()).thenReturn(Response.Status.OK); - @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 response = aaiClientMock.getTenantsNonCached("subscriberId", "serviceType"); - when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(generalEmptyResponse); + GetTenantsResponse[] tenants = response.getT(); - AaiResponse response = aaiClientMock.getTenants("subscriberId", "serviceType"); + Assert.assertTrue(response.t.length> 0); - Assert.assertTrue(response.t.length > 0); + Assert.assertEquals(tenants[0].cloudOwner,"att-aic-cloud-owner"); } - final String tenantResponseRaw = "" + + final String tenantResponseRaw ="" + "{" + "\"service-type\": \"VIRTUAL USP\"," + "\"resource-version\": \"1494001841964\"," + @@ -285,7 +338,7 @@ public class AaiClientTest { "\"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-value\": \"att-aic-cloud-owner\"" + "}," + "{" + "\"relationship-key\": \"cloud-region.cloud-region-id\"," + @@ -304,51 +357,179 @@ public class AaiClientTest { "}" + "}"; + final String vfModuleHomingResponseRaw ="{" + + " \"vf-module-id\": \"ed02354a-3217-45ce-a1cd-e0b69b7a8cea\"," + + " \"vf-module-name\": \"apndns_az_02_module_1\"," + + " \"heat-stack-id\": \"apndns_az_02_module_1/97a319f3-b095-4fff-befa-c657508ecaf8\"," + + " \"orchestration-status\": \"active\"," + + " \"is-base-vf-module\": false," + + " \"resource-version\": \"1530559380383\"," + + " \"model-invariant-id\": \"74450b48-0aa0-4743-8314-9163e92b7862\"," + + " \"model-version-id\": \"6bc01a2b-bc48-4991-b9fe-e22c2215d801\"," + + " \"model-customization-id\": \"74f638c2-0368-4212-8f73-e961005af17c\"," + + " \"module-index\": 0," + + " \"relationship-list\": {" + + " \"relationship\": [" + + " {" + + " \"related-to\": \"l3-network\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/335e62be-73a3-41e8-930b-1a677bcafea5\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"l3-network.network-id\"," + + " \"relationship-value\": \"335e62be-73a3-41e8-930b-1a677bcafea5\"" + + " }" + + " ]," + + " \"related-to-property\": [" + + " {" + + " \"property-key\": \"l3-network.network-name\"," + + " \"property-value\": \"MNS-FN-25180-T-02Shared_oam_protected_net_1\"" + + " }" + + " ]" + + " }," + + " {" + + " \"related-to\": \"l3-network\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.DependsOn\"," + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"l3-network.network-id\"," + + " \"relationship-value\": \"2db4ee3e-2ac7-4fc3-8739-ecf53416459e\"" + + " }" + + " ]," + + " \"related-to-property\": [" + + " {" + + " \"property-key\": \"l3-network.network-name\"," + + " \"property-value\": \"Mobisupport-FN-27099-T-02_int_apn_dns_net_1\"" + + " }" + + " ]" + + " }," + + " {" + + " \"related-to\": \"volume-group\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + + " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"cloud-region.cloud-owner\"," + + " \"relationship-value\": \"att-aic\"" + + " }," + + " {" + + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + + " \"relationship-value\": \"rdm5b\"" + + " }," + + " {" + + " \"relationship-key\": \"volume-group.volume-group-id\"," + + " \"relationship-value\": \"66013ebe-0c81-44b9-a24f-7c6acba73a39\"" + + " }" + + " ]" + + " }," + + " {" + + " \"related-to\": \"vserver\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + + " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," + + " \"relationship-data\": [" + + " {" + + " \"relationship-key\": \"cloud-region.cloud-owner\"," + + " \"relationship-value\": \"att-aic\"" + + " }," + + " {" + + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + + " \"relationship-value\": \"rdm5b\"" + + " }," + + " {" + + " \"relationship-key\": \"tenant.tenant-id\"," + + " \"relationship-value\": \"db1818f7f2e34862b378bfb2cc520f91\"" + + " }," + + " {" + + " \"relationship-key\": \"vserver.vserver-id\"," + + " \"relationship-value\": \"5eef9f6d-9933-4bc6-9a1a-862d61309437\"" + + " }" + + " ]," + + " \"related-to-property\": [" + + " {" + + " \"property-key\": \"vserver.vserver-name\"," + + " \"property-value\": \"zrdm5bfapn01dns002\"" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + "}"; + @Test + public void get_homingDataForVfModule() { + when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod(); + + Response homingResponse = mock(Response.class); + + when(homingResponse.readEntity(String.class)).thenReturn(vfModuleHomingResponseRaw); + when(homingResponse.getStatus()).thenReturn(200); + when(homingResponse.getStatusInfo()).thenReturn(Response.Status.OK); + + + when(aaiClientMock.doAaiGet(any(String.class), any(Boolean.class))).thenReturn(homingResponse); + + GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId"); + + Assert.assertEquals(tenant.cloudOwner,"att-aic"); + Assert.assertEquals(tenant.cloudRegionID,"rdm5b"); + Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91"); + + } + @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "A&AI has no homing data associated to vfModule 'vfModuleId' of vnf 'vnfInstanceId'") + public void getVfMoudule_Homing_Arguments_Are_Valid_But_Not_Exists() { + when(aaiClientMock.getHomingDataByVfModule(any(String.class), any(String.class))).thenCallRealMethod(); + + Response generalEmptyResponse = mock(Response.class); + when(aaiClientMock.doAaiGet(any(String.class),any(Boolean.class))).thenReturn(generalEmptyResponse); + + aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId"); + } + @DataProvider - public static Object[][] resourceTypesProvider() { - return new Object[][]{ - {"service-instance", ResourceType.SERVICE_INSTANCE}, - {"generic-vnf", ResourceType.GENERIC_VNF}, - {"vf-module", ResourceType.VF_MODULE} + public static Object[][] invalidDataId() { + return new String[][] { + {""}, + {null} }; } - @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(dataProvider = "invalidDataId", expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = "Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.") + public void getVfMoudule_Homing_Arguments_Are_Empty_Or_Null(String data) { + when(aaiClientMock.getHomingDataByVfModule(any(), any())).thenCallRealMethod(); + aaiClientMock.getHomingDataByVfModule(data, data); } - @Test - public void aaiNodeQueryEmptyResponseDeserializationTest() throws IOException { - String json = "{}"; - AaiNodeQueryResponse nodeQueryResponse = new ObjectMapper().readValue(json, AaiNodeQueryResponse.class); - assertNull(nodeQueryResponse.resultData); + @DataProvider + public static Object[][] resourceTypesProvider() { + return new Object[][] { + {"service-instance", ResourceType.SERVICE_INSTANCE}, + {"generic-vnf", ResourceType.GENERIC_VNF}, + {"vf-module", ResourceType.VF_MODULE} + }; } @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"} + return new Object[][] { + {"SRIOV_SVC", ResourceType.SERVICE_INSTANCE, "nodes/service-instances?service-instance-name=SRIOV_SVC"}, + {"b1707vidnf", ResourceType.GENERIC_VNF, "nodes/generic-vnfs?vnf-name=b1707vidnf"}, + {"connectivity_test", ResourceType.VF_MODULE, "nodes/vf-modules?vf-module-name=connectivity_test"}, + {"ByronPace", ResourceType.INSTANCE_GROUP, "nodes/instance-groups?instance-group-name=ByronPace"}, + {"MjVg1234", ResourceType.VOLUME_GROUP, "nodes/volume-groups?volume-group-name=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)); + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, "{}"); + + when(aaiRestInterface.RestGet(anyString(), anyString(), eq(toURI(expectedUrl)), anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + + AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + aaiClient.isNodeTypeExistsByName(name, type); } @DataProvider @@ -381,20 +562,20 @@ public class AaiClientTest { // Exception out of javax's Client Pair.of(SSLHandshakeException.class, (httpsAuthClientMock, javaxClientMock) -> { - when(javaxClientMock.target(anyString())).thenThrow( + when(javaxClientMock.target(nullable(String.class))).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( + when(javaxClientMock.target(nullable(String.class))).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"))) + when(javaxClientMock.target(nullable(String.class))).thenThrow(new GenericUncheckedException("basa"))) ).flatMap(l -> Stream.of( // double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work @@ -426,8 +607,8 @@ public class AaiClientTest { Response responseMock = mocks.getFakeResponse(); // prepare real AAIRestInterface and AaiClient, and wire mocks - AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock, new ServletRequestHelper(), new SystemPropertyHelper()); - final AaiClient aaiClient = new AaiClient(aaiRestInterface, null); + AAIRestInterface aaiRestInterface = new AAIRestInterface(httpsAuthClientMock, mock(ServletRequestHelper.class), mock(SystemPropertyHelper.class)); + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); when(httpsAuthClientMock.getClient(any())).thenReturn(javaxClientMock); // define atomic method under test, including reset of "aaiRestInterface.client" @@ -465,6 +646,121 @@ public class AaiClientTest { assertFalse(propagateExceptions, "calling doAaiGet when propagateExceptions is 'true' must result with an exception (in this test)"); } + @DataProvider + public static Object[][] aaiClientGetCloudOwnerByCloudRegionId() { + + final String cloudRegion = "{" + + " \"cloud-owner\": \"mure-royo-ru22\"," + + " \"cloud-region-id\": \"ravitu\"," + + " \"cloud-type\": \"openstack\"," + + " \"resource-version\": \"1523631256125\"," + + " \"relationship-list\": {" + + " \"relationship\": [{" + + " \"related-to\": \"pserver\"" + + " }" + + " ]" + + " }" + + " }"; + + String bodyWith0 = "{ \"cloud-region\": [" + " ]}"; + String bodyWith1 = "{ \"cloud-region\": [" + cloudRegion + " ]}"; + String bodyWith2 = "{ \"cloud-region\": [" + cloudRegion + ", " + cloudRegion + " ]}"; + String bodyWithDifferent2 = "{ \"cloud-region\": [" + cloudRegion + ", " + + cloudRegion.replace("mure-royo-ru22", "nolay-umaxo") + + "]}"; + + return new Object[][] { + { "regular single result", bodyWith1, false }, + { "exceptional empty result", bodyWith0, true }, + { "two same results", bodyWith2, false }, + { "two incoherent results", bodyWithDifferent2, true }, + }; + } + + @Test(dataProvider = "aaiClientGetCloudOwnerByCloudRegionId") + public void getCloudOwnerByCloudRegionIdNonCached(String desc, String body, boolean expectingException) { + final String cloudRegion = "ravitu"; + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, body); + when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("cloud-infrastructure/cloud-regions?cloud-region-id=" + cloudRegion)), + isNull(), eq(HttpMethod.GET), anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + + try { + final String result = aaiClient.getCloudOwnerByCloudRegionIdNonCached(cloudRegion); + if (expectingException) fail("expected failure on " + desc + ", got " + result); + else { + assertThat(result, is("mure-royo-ru22")); + } + } catch (Exception e) { + if (!expectingException) throw e; + else { + assertThat(e.toString(), either( + containsString("No cloud-owner found for " + cloudRegion)) + .or(containsString("Conflicting cloud-owner found for " + cloudRegion))); + } + } + } + + @DataProvider + public static Object[][] cloudRegionAndTenantDataProvider() { + return new Object[][] { + { "APPC-24595-T-IST-02C", "mtn23b" }, + { "APPC-24595-T-IST-02C", null }, + { null, "mtn23b" }, + { null, null }, + }; + } + + @Test(dataProvider = "cloudRegionAndTenantDataProvider") + public void getCloudRegionAndTenantByVnfId(String tenantName, String cloudRegionId) throws JsonProcessingException { + SimpleResult tenant = new SimpleResult(); + if (tenantName != null) { + tenant.setJsonNodeType("tenant"); + Properties tenantProps = new Properties(); + tenantProps.setTenantName(tenantName); + tenant.setJsonProperties(tenantProps); + } + + SimpleResult cloudRegion = new SimpleResult(); + if (cloudRegionId != null) { + cloudRegion.setJsonNodeType("cloud-region"); + Properties cloudRegionProps = new Properties(); + cloudRegionProps.setCloudRegionId(cloudRegionId); + cloudRegion.setJsonProperties(cloudRegionProps); + } + + CustomQuerySimpleResult customQuerySimpleResult = new CustomQuerySimpleResult(ImmutableList.of(tenant, cloudRegion)); + String mockedBody = new ObjectMapper().writeValueAsString(customQuerySimpleResult); + + AAIRestInterface aaiRestInterface = mock(AAIRestInterface.class); + final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK, mockedBody, "query?format=simple", HttpMethod.PUT); + when(aaiRestInterface.doRest(anyString(), anyString(), eq(Unchecked.toURI("query?format=simple")), + any(), eq(HttpMethod.PUT), anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + + final AaiClient aaiClient = new AaiClient(aaiRestInterface, null, null); + Map result = aaiClient.getCloudRegionAndTenantByVnfId("anyVnfId"); + if (tenantName != null) { + assertEquals(result.get("tenant").getTenantName(), tenantName); + } else { + assertNull(result.get("tenant")); + } + + if (cloudRegionId != null) { + assertEquals(result.get("cloud-region").getCloudRegionId(), cloudRegionId); + } else { + assertNull(result.get("cloud-region")); + } + } + + protected void mockForGetRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) { + when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), isNull(), eq(HttpMethod.GET) ,anyBoolean(), anyBoolean())) + .thenReturn(responseWithRequestInfo); + } + @Test public void shouldProperlyReadResponseOnceWhenSubscribersAreNotPresent() { AAIRestInterface restInterface = mock(AAIRestInterface.class); @@ -475,8 +771,8 @@ public class AaiClientTest { when(response.getStatusInfo()).thenReturn(Response.Status.NOT_FOUND); ResponseWithRequestInfo responseWithRequestInfo = new ResponseWithRequestInfo(response, "test", HttpMethod.GET); when(restInterface.RestGet(eq("VidAaiController"), any(String.class), - eq("business/customers?subscriber-type=INFRA&depth=0"), eq(false), eq(true))).thenReturn(responseWithRequestInfo); - AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator); + eq(Unchecked.toURI("business/customers?subscriber-type=INFRA&depth=0")), eq(false), eq(true))).thenReturn(responseWithRequestInfo); + AaiClient aaiClient = new AaiClient(restInterface, portDetailsTranslator, null); aaiClient.getAllSubscribers(true); @@ -497,4 +793,5 @@ public class AaiClientTest { void acceptThrows(T t, U u) throws Exception; } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java index d4f59e7da..da08ed866 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientServerTest.java @@ -34,7 +34,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.aai.model.AaiNodeQueryResponse; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.client.SyncRestClient; import org.onap.vid.model.SubscriberList; @@ -50,31 +49,15 @@ public class AaiOverTLSClientServerTest { private static StubServerUtil serverUtil; - private String searchNodesQueryResponsePayload = - "{\n" - + "\"result-data\": [\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6eac8e69-c98d-4ac5-ab90-69fe0cabda76\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/e3766bc5-40a7-4dbe-9d4a-1d8c8f284913\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6aa153ee-6637-4b49-beb5-a5e756e00393\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/5a981c30-de25-4ea9-98fa-ed398f13ea41\"\n" - + "},\n" - + " {\n" - + "\"resource-type\": \"generic-vnf\",\n" - + "\"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/b0ef2271-8ac0-4268-b9a5-09cb50c20c85\"\n" - + "}\n" - + "],\n" - + "}"; + private String searchNodesQueryResponsePayload = "" + + "{" + + "\"result-data\": [" + + " {" + + " \"resource-type\": \"generic-vnf\"," + + " \"resource-link\": \"/aai/v13/network/generic-vnfs/generic-vnf/6eac8e69-c98d-4ac5-ab90-69fe0cabda76\"" + + " }" + + " ]" + + "}"; private String subscribersResponsePayload = "{\n" @@ -122,19 +105,17 @@ public class AaiOverTLSClientServerTest { ObjectMapper objectMapper = getFasterXmlObjectMapper(); AaiOverTLSClient aaiOverTLSClient = new AaiOverTLSClient(new SyncRestClient(objectMapper), propertySupplier, serverUtil.constructTargetUrl("http", "")); - serverUtil.prepareGetCall("/search/nodes-query", new JSONParser().parse(searchNodesQueryResponsePayload), Action.status(HttpStatus.OK_200)); + serverUtil.prepareGetCall("/nodes/generic-vnfs", new JSONParser().parse(searchNodesQueryResponsePayload), Action.status(HttpStatus.OK_200)); - HttpResponse aaiNodeQueryResponseHttpResponse = aaiOverTLSClient - .searchNodeTypeByName("any", ResourceType.GENERIC_VNF); + boolean aaiNodeQueryResponseHttpResponse = aaiOverTLSClient + .isNodeTypeExistsByName("any", ResourceType.GENERIC_VNF); - AaiNodeQueryResponse body = aaiNodeQueryResponseHttpResponse.getBody(); - Assertions.assertThat(body.resultData.size()).isEqualTo(5); - Assertions.assertThat(aaiNodeQueryResponseHttpResponse.getStatus()).isEqualTo(200); + Assertions.assertThat(aaiNodeQueryResponseHttpResponse).isEqualTo(true); } @Test public void shouldGetSubscribers() throws ParseException, JsonProcessingException { - ObjectMapper objectMapper = getCodehausObjectMapper(); + ObjectMapper objectMapper = getFasterXmlObjectMapper(); AaiOverTLSClient aaiOverTLSClient = new AaiOverTLSClient(new SyncRestClient(objectMapper), propertySupplier, serverUtil.constructTargetUrl("http", "")); serverUtil.prepareGetCall("/business/customers", new JSONParser().parse(subscribersResponsePayload), Action.status(HttpStatus.OK_200)); @@ -146,31 +127,6 @@ public class AaiOverTLSClientServerTest { Assertions.assertThat(allSubscribers.getStatus()).isEqualTo(200); } - private ObjectMapper getCodehausObjectMapper() { - return new ObjectMapper() { - - org.codehaus.jackson.map.ObjectMapper om = new org.codehaus.jackson.map.ObjectMapper(); - - @Override - public T readValue(String s, Class aClass) { - try { - return om.readValue(s, aClass); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public String writeValue(Object o) { - try { - return om.writeValueAsString(o); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - }; - } - private ObjectMapper getFasterXmlObjectMapper() { return new ObjectMapper() { diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java index f281e84b6..52556a1a3 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiOverTLSClientTest.java @@ -24,10 +24,10 @@ import com.google.common.collect.ImmutableMap; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Answers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.onap.vid.aai.model.AaiNodeQueryResponse; import org.onap.vid.aai.model.ResourceType; import org.onap.vid.client.SyncRestClient; import org.onap.vid.model.SubscriberList; @@ -41,11 +41,11 @@ import static org.mockito.ArgumentMatchers.eq; @RunWith(MockitoJUnitRunner.class) public class AaiOverTLSClientTest { - private static final String SEARCH_NODES_QUERY_SEARCH_NODE_TYPE = "search/nodes-query?search-node-type=generic-vnf&filter=vnf-name:EQUALS:name"; + private static final String SEARCH_NODES_QUERY_SEARCH_NODE_TYPE = "nodes/generic-vnfs?vnf-name=name"; private static final String SUBSCRIBERS = "business/customers?subscriber-type=INFRA&depth=0"; private AaiOverTLSClient aaiRestClient; - @Mock + @Mock(answer = Answers.RETURNS_MOCKS) private SyncRestClient syncRestClient; @Mock private AaiOverTLSPropertySupplier propertySupplier; @@ -56,12 +56,12 @@ public class AaiOverTLSClientTest { } @Test - public void testSearchNodeTypeByName() { + public void testIsNodeTypeExistsByName() { mockPropertyReader(); - aaiRestClient.searchNodeTypeByName("name", ResourceType.GENERIC_VNF); + aaiRestClient.isNodeTypeExistsByName("name", ResourceType.GENERIC_VNF); Mockito.verify(syncRestClient).get(contains(SEARCH_NODES_QUERY_SEARCH_NODE_TYPE), - eq(getHeaders()), eq(Collections.emptyMap()), eq(AaiNodeQueryResponse.class)); + eq(getHeaders()), eq(Collections.emptyMap())); } @Test diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java index c2ccec008..3d649bb69 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/OperationalEnvironmentTest.java @@ -2,8 +2,6 @@ package org.onap.vid.aai; import org.junit.Test; import org.onap.vid.aai.model.RelationshipList; -import java.util.*; -import org.junit.Assert; public class OperationalEnvironmentTest { @@ -28,7 +26,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentId(operationalEnvironmentId); + testSubject.setJsonOperationalEnvironmentId(operationalEnvironmentId); } @Test @@ -48,7 +46,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentName(operationalEnvironmentName); + testSubject.setJsonOperationalEnvironmentName(operationalEnvironmentName); } @Test @@ -68,7 +66,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentType(operationalEnvironmentType); + testSubject.setJsonOperationalEnvironmentType(operationalEnvironmentType); } @Test @@ -88,7 +86,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setOperationalEnvironmentStatus(operationalEnvironmentStatus); + testSubject.setJsonOperationalEnvironmentStatus(operationalEnvironmentStatus); } @Test @@ -108,7 +106,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setTenantContext(tenantContext); + testSubject.setJsonTenantContext(tenantContext); } @Test @@ -128,7 +126,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setWorkloadContext(workloadContext); + testSubject.setJsonWorkloadContext(workloadContext); } @Test @@ -148,7 +146,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setResourceVersion(resourceVersion); + testSubject.setJsonResourceVersion(resourceVersion); } @Test @@ -168,7 +166,7 @@ public class OperationalEnvironmentTest { // default test testSubject = createTestSubject(); - testSubject.setRelationshipList(relationshipList); + testSubject.setJsonRelationshipList(relationshipList); } @Test diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java index 2b7a60429..72a5e193e 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/VnfResultTest.java @@ -1,10 +1,10 @@ package org.onap.vid.aai; -import java.util.Map; - import org.junit.Test; import org.onap.vid.aai.model.VnfResult; +import java.util.Map; + public class VnfResultTest { private VnfResult createTestSubject() { @@ -29,6 +29,5 @@ public class VnfResultTest { // default test testSubject = createTestSubject(); - testSubject.setAdditionalProperty(name, value); } } \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java index 7b5b8aa39..d7394632a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/AaiGetPnfResponseTest.java @@ -1,15 +1,15 @@ package org.onap.vid.aai.model; -import java.io.IOException; -import java.util.ArrayList; - -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; +import java.io.IOException; +import java.util.ArrayList; + import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.StringContains.containsString; import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.StringContains.containsString; public class AaiGetPnfResponseTest { diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java index e2a62c0e8..a59b52078 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfPropertiesTest.java @@ -1,13 +1,11 @@ package org.onap.vid.aai.model; -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; import java.io.IOException; -import java.util.ArrayList; -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringContains.containsString; diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java index 912eea9d7..4f2762c32 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/model/PnfResultTest.java @@ -1,11 +1,11 @@ package org.onap.vid.aai.model; -import java.io.IOException; - -import org.codehaus.jackson.map.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Before; import org.junit.Test; +import java.io.IOException; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.StringContains.containsString; diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java new file mode 100644 index 000000000..1faaee3aa --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheConfigTest.java @@ -0,0 +1,32 @@ +package org.onap.vid.aai.util; + +import org.testng.annotations.Test; + +import static org.testng.AssertJUnit.assertEquals; + +public class CacheConfigTest { + + @Test + public void whenDeserializeJson_ValuesReadAsExpected() { + CacheConfigProvider cacheConfigProvider = new CacheConfigProviderImpl(); + CacheConfig cacheConfigA = cacheConfigProvider.getCacheConfig("a"); + assertEquals(true, cacheConfigA.isActive()); + assertEquals(6L, cacheConfigA.getExpireAfterWriteHours()); + assertEquals(9L, cacheConfigA.getRefreshAfterWriteSeconds()); + + //entry exist in configuration, but with no values + CacheConfig cacheConfigB = cacheConfigProvider.getCacheConfig("b"); + assertEquals(cacheConfigB.isActive(), CacheConfig.Companion.getDefaultCacheConfig().isActive()); + assertEquals(cacheConfigB.getExpireAfterWriteHours(), CacheConfig.Companion.getDefaultCacheConfig().getExpireAfterWriteHours()); + assertEquals(cacheConfigB.getRefreshAfterWriteSeconds(), CacheConfig.Companion.getDefaultCacheConfig().getRefreshAfterWriteSeconds()); + + + //entry doesn't exist in configuration + CacheConfig cacheConfigC = cacheConfigProvider.getCacheConfig("c"); + assertEquals(CacheConfig.Companion.getDefaultCacheConfig(), cacheConfigC); + + CacheConfig cacheConfigD = cacheConfigProvider.getCacheConfig("d"); + assertEquals(false, cacheConfigD.isActive()); + + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java new file mode 100644 index 000000000..95daf9038 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderTest.java @@ -0,0 +1,41 @@ +package org.onap.vid.aai.util; + +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.onap.vid.aai.util.CacheProvider.compileKey; +import static org.onap.vid.aai.util.CacheProvider.decompileKey; + +public class CacheProviderTest { + @Test(dataProvider = "aaiClientCompileDecompileKeySameData") + public void compileDecompileKeySameTest(List args) { + assertThat(decompileKey(compileKey(args)), is(args.toArray())); + } + + @Test(dataProvider = "aaiClientCompileDecompileKeyDifferentData") + public void compileDecompileKeyDifferentTest(List expectedResult, List args) { + assertThat(decompileKey(compileKey(args)), is(expectedResult.toArray())); + } + + @DataProvider + public static Object[][] aaiClientCompileDecompileKeySameData() { + return new Object[][] { + {Arrays.asList( "a", "b", "c")}, + {Arrays.asList("a")}, + {Arrays.asList("a!", "@#?b")}, + {Arrays.asList("a", "", "c")} + }; + } + + @DataProvider + public static Object[][] aaiClientCompileDecompileKeyDifferentData() { + return new Object[][] { + {Arrays.asList("a", "", "c"), Arrays.asList("a", null, "c")} + }; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java new file mode 100644 index 000000000..9a9b28905 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/CacheProviderWithLoadingCacheTest.java @@ -0,0 +1,313 @@ +package org.onap.vid.aai.util; + +import com.google.common.cache.CacheBuilder; +import com.google.common.collect.ImmutableList; +import org.apache.commons.lang3.RandomUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.properties.Features; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; + +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Function; + +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.*; +import static org.hamcrest.core.Is.is; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.*; +import static org.testng.AssertJUnit.assertEquals; + +public class CacheProviderWithLoadingCacheTest { + private final FeatureManager featureManager = mock(FeatureManager.class); + private final CacheConfigProvider cacheConfigProvider = mock(CacheConfigProvider.class); + + @BeforeMethod + public void activateCacheFeatureFlag() { + reset(featureManager); + when(featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(true); + when(cacheConfigProvider.getCacheConfig(any())).thenReturn(CacheConfig.Companion.getDefaultCacheConfig()); + } + + private CacheProviderWithLoadingCache createNewCacheProvider() { + return new CacheProviderWithLoadingCache(featureManager, cacheConfigProvider); + } + + private String RAND() { + return randomAlphanumeric(5); + } + + @Test + public void cacheProvider_requestingCache_CreatesNewCache() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 4); + + assertThat(integerIntegerCache, notNullValue()); + assertThat(integerIntegerCache.get(5), is(9)); + } + + @Test + public void cacheProvider_requestingCacheSameNameTwice_ReturnsFirstCacheInstance() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final String name = RAND(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(name, (Integer i) -> i + 4); + final CacheProvider.Cache integerIntegerCache2 = provider.aaiClientCacheFor(name, (Integer i) -> i + 6); + + assertThat(integerIntegerCache2, sameInstance(integerIntegerCache)); + assertThat(integerIntegerCache.get(5), is(9)); // as the first one + } + + @Test + public void cacheProvider_requestingCacheSameNameTwiceOutOfSeveral_ReturnsFirstCacheInstance() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + + final String name = RAND(); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 2); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 3); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(name, (Integer i) -> i + 4); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 5); + provider.aaiClientCacheFor(RAND(), (Integer i) -> i + 6); + final CacheProvider.Cache integerIntegerCache2 = provider.aaiClientCacheFor(name, (Integer i) -> i + 4); + + assertThat(integerIntegerCache2, sameInstance(integerIntegerCache)); + } + + @Test + public void cacheProvider_sameProviderSupportDifferentKV() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + + assertThat(provider.aaiClientCacheFor(RAND(), + (Integer i) -> i + 2).get(0), is(2)); + assertThat(provider.aaiClientCacheFor(RAND(), + (Integer i) -> i + 3).get(0), is(3)); + assertThat(provider.aaiClientCacheFor(RAND(), + (String s) -> s + 5).get("0"), is("05")); + assertThat(provider.aaiClientCacheFor(RAND(), + (Integer i) -> "0" + i).get(0), is("00")); + assertThat(provider.aaiClientCacheFor(RAND(), + (Pair p) -> ImmutableList.of(p.getLeft(), p.getRight())).get(Pair.of(7, "B")), contains(7, "B")); + } + + @Test + public void cache_callMultiTimesGetFromCahce_loaderCalledOncePairValue(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> RandomUtils.nextInt()); + int key = RandomUtils.nextInt(); + Integer result1 = integerIntegerCache.get(key); + Integer result2 = integerIntegerCache.get(key + 1); + Integer result3 = integerIntegerCache.get(key); + + Assert.assertNotEquals(result1,result2); + Assert.assertEquals(result1,result3); + } + + @Test + public void cache_callMultiTimesGetFromCahce_loaderCalledOnce(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> { + counter.increment(); + return i; + }); + + int key = RandomUtils.nextInt(); + Integer result1 = integerIntegerCache.get(key); + Integer result2 = integerIntegerCache.get(key); + Integer result3 = integerIntegerCache.get(key); + + Assert.assertEquals(result1.intValue(),key); + Assert.assertEquals(result2.intValue(),key); + Assert.assertEquals(result3.intValue(),key); + Assert.assertEquals(counter.intValue(),1); + } + + @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp ="boom" ) + public void cache_inCaseLoaderMethodThrowsException_cacheThrowsSameException(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache stringIntegerCache = provider.aaiClientCacheFor(RAND(), (String s) -> { throw new GenericUncheckedException("boom");}); + + stringIntegerCache.get("Whatever"); + } + + @Test + public void cache_inCaseLoaderMethodThrowsException_nextCallUseLoaderMethod(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), new Function() { + private boolean firstTime = true; + @Override + public Integer apply(Integer i) { + if (firstTime) { + firstTime = false; + throw new GenericUncheckedException("boom"); + } + else { + return i; + } + } + }); + + try { + integerIntegerCache.get(1); + } + catch (GenericUncheckedException e) {} + + assertEquals(new Integer(1), integerIntegerCache.get(1)); + } + + @Test + public void cache_getIsCalledMoreThanOnce_loaderNotCalledAgainForSameInputValue(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(RAND(), (Integer i) -> { counter.increment(); return i; }); + + int key1 = RandomUtils.nextInt(); + int key2 = RandomUtils.nextInt(); + integerIntegerCache.get(key1); + Assert.assertEquals(counter.intValue(),1); + integerIntegerCache.get(key2); + Assert.assertEquals(counter.intValue(),2); + integerIntegerCache.get(key1); + Assert.assertEquals(counter.intValue(),2); + } + + @Test + public void cache_getIsCalledMoreThanOnce_loaderIsCalledAgainAfterReset(){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + String cacheName = RAND(); + + int key1 = RandomUtils.nextInt(); + provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1); + Assert.assertEquals(counter.intValue(), 1); + provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1); + Assert.assertEquals(counter.intValue(), 1); + + provider.resetCache(cacheName); + provider.aaiClientCacheFor(cacheName, (Integer i) -> { counter.increment(); return i; }).get(key1); + Assert.assertEquals(counter.intValue(), 2); + + } + + + public static class TestData { + public FeatureManager featureManager; + public String cacheName; + public CacheConfigProvider cacheConfigProvider; + + public TestData(FeatureManager featureManager, String cacheName, CacheConfigProvider cacheConfigProvider) { + this.featureManager = featureManager; + this.cacheName = cacheName; + this.cacheConfigProvider = cacheConfigProvider; + } + } + + + @DataProvider + public static Object[][] mockForCacheIsNotActive() { + + Consumer mockFeatureOff = (testData)->{ + when(testData.featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(false); + when(testData.cacheConfigProvider.getCacheConfig(testData.cacheName)).thenReturn(new CacheConfig(true, 10L, 10L)); + }; + Consumer mockFeatureOnCacheOff = (testData)->{ + when(testData.featureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(true); + when(testData.cacheConfigProvider.getCacheConfig(testData.cacheName)).thenReturn(new CacheConfig(false, 10L, 10L)); + }; + + + return new Object[][]{ + {mockFeatureOff}, + {mockFeatureOnCacheOff} + }; + } + + + @Test(dataProvider = "mockForCacheIsNotActive") + public void cache_featureFlagToggleIsOff_loaderIsCalledForEachGet(Consumer mocker){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final MutableInt counter = new MutableInt(); + String cacheName = RAND(); + + final CacheProvider.Cache integerIntegerCache = provider.aaiClientCacheFor(cacheName, (Integer i) -> { + counter.increment(); + return i; + }); + + mocker.accept(new TestData(featureManager, cacheName, cacheConfigProvider)); + counter.setValue(0); + int key = RandomUtils.nextInt(); + integerIntegerCache.get(key); + integerIntegerCache.get(key); + + Assert.assertEquals(counter.intValue(),2); + } + + @Test + public void cache_loaderReturnsRandomValue_sameValueIsReturnedForSameKey() { + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final String name = RAND(); + final CacheProvider.Cache integerRandomStringCache = provider.aaiClientCacheFor(name, (Integer i) -> RAND()); + + String firstGet = integerRandomStringCache.get(1); + String secondGet = integerRandomStringCache.get(1); + + Assert.assertEquals(firstGet,secondGet); + } + + @Test(dataProvider = "mockForCacheIsNotActive") + public void cache_toggleFlagOff_ResetCache(Consumer mocker){ + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + final String cacheName = RAND(); + final CacheProvider.Cache integerRandomStringCache = provider.aaiClientCacheFor(cacheName, (Integer i) -> RAND()); + int key = RandomUtils.nextInt(); + String result1 = integerRandomStringCache.get(key); + String result2 = integerRandomStringCache.get(key); + Assert.assertEquals(result1,result2); + + mocker.accept(new TestData(featureManager, cacheName, cacheConfigProvider)); + String result3 = integerRandomStringCache.get(key); + Assert.assertNotEquals(result1, result3); + } + + @DataProvider + public static Object[][] mockForCacheBuilderConfig() { + return new Object[][]{ + {2L, 2L, 3L, 3L}, + {null, 10L, null, 24L} //null meaning use the default, which is 10L,24L + }; + } + + @Test(dataProvider = "mockForCacheBuilderConfig") + public void cacheBuilderConfiguredWithValues_andWithDefaults( + Long refreshAfterWriteSeconds, + long expectedRefreshAfterWriteSeconds, + Long expireAfterWriteHours, + long expectedExpireAfterWriteHours + ) throws IllegalAccessException { + final String cacheName = RAND(); + when(cacheConfigProvider.getCacheConfig(cacheName)).thenReturn(new CacheConfig(true, expireAfterWriteHours, refreshAfterWriteSeconds)); + final CacheProviderWithLoadingCache provider = createNewCacheProvider(); + CacheBuilder cacheBuilder = provider.createCacheBuilder(cacheName); + + + //Unfortunately CacheBuilder doesn't expose public getters + //Since it's only unit test I let myself do some fouls and use reflection + Long actualRefreshNanos = (Long)FieldUtils.readDeclaredField(cacheBuilder, "refreshNanos", true); + assertThat(actualRefreshNanos, equalTo(TimeUnit.NANOSECONDS.convert(expectedRefreshAfterWriteSeconds, TimeUnit.SECONDS))); + + Long actualExpireAfterWriteNanos = (Long)FieldUtils.readDeclaredField(cacheBuilder, "expireAfterWriteNanos", true); + assertThat(actualExpireAfterWriteNanos, equalTo(TimeUnit.NANOSECONDS.convert(expectedExpireAfterWriteHours, TimeUnit.HOURS))); + + } +} + 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 ce957ab67..44678ec24 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 @@ -21,11 +21,20 @@ package org.onap.vid.aai.util; +import org.junit.Before; +import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.aai.exceptions.HttpClientBuilderException; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.togglz.core.manager.FeatureManager; import javax.net.ssl.SSLContext; +import java.util.Optional; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class HttpsAuthClientTest { @@ -38,47 +47,43 @@ public class HttpsAuthClientTest { public static final String CERT_FILE_PATH = "any_path"; - /* - TO BE IMPLEMENTED - private HttpsAuthClient createTestSubject() { - return new HttpsAuthClient(systemPropertyHelper, sslContextProvider); + return new HttpsAuthClient(CERT_FILE_PATH, systemPropertyHelper, sslContextProvider, mock(FeatureManager.class)); } @Before public void setUp() throws Exception { when(systemPropertyHelper.getAAITruststoreFilename()).thenReturn(Optional.of("filename")); - when(systemPropertyHelper.getEncodedTruststorePassword()).thenReturn("password"); + when(systemPropertyHelper.getDecryptedKeystorePassword()).thenReturn("password"); + when(systemPropertyHelper.getDecryptedTruststorePassword()).thenReturn("password"); } @Test(expected = HttpClientBuilderException.class) - public void testHttpClientBuilderExceptionOnGetClient() throws HttpClientBuilderException { + public void testHttpClientBuilderExceptionOnGetClient() throws Exception { //when - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("true")); - when(sslContextProvider.getSslContext(anyString(), anyString())).thenThrow(new HttpClientBuilderException()); - createTestSubject().getClient("nonExistingFile"); + when(systemPropertyHelper.isClientCertEnabled()).thenReturn(true); + when(sslContextProvider.getSslContext(anyString(), anyString(), any())).thenThrow(new HttpClientBuilderException(new GenericUncheckedException("msg"))); + createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE); } @Test public void testGetSecuredClient() throws Exception { // when - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("true")); - when(sslContextProvider.getSslContext(anyString(), anyString())).thenReturn(sslContext); - createTestSubject().getClient(CERT_FILE_PATH); + when(systemPropertyHelper.isClientCertEnabled()).thenReturn(true); + when(sslContextProvider.getSslContext(anyString(), anyString(), any())).thenReturn(sslContext); + createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE); //then - verify(sslContextProvider).getSslContext(anyString(), anyString()); + verify(sslContextProvider).getSslContext(anyString(), anyString(), any()); } @Test public void testGetUnsecuredClient() throws Exception { // when - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("false")); - when(sslContextProvider.getSslContext(anyString(), anyString())).thenReturn(sslContext); - createTestSubject().getClient(CERT_FILE_PATH); + when(systemPropertyHelper.isClientCertEnabled()).thenReturn(false); + createTestSubject().getClient(HttpClientMode.WITH_KEYSTORE); //then - verify(sslContextProvider, never()).getSslContext(anyString(), anyString()); + verify(sslContextProvider, never()).getSslContext(anyString(), anyString(), any()); } - */ } \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java new file mode 100644 index 000000000..b43370763 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/NonCachingCacheProvider.java @@ -0,0 +1,14 @@ +package org.onap.vid.aai.util; + +import java.util.function.Function; + +public class NonCachingCacheProvider implements CacheProvider { + + @Override + public Cache aaiClientCacheFor(String name, Function loader) { + return loader::apply; + } + + @Override + public void resetCache(String name) {} +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java new file mode 100644 index 000000000..99cd928c2 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/ServiceInstanceStandardQueryTest.java @@ -0,0 +1,405 @@ +package org.onap.vid.aai.util; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableList; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Network; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vlan; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Vnf; +import org.onap.vid.utils.Multival; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.web.client.HttpClientErrorException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.net.URI; +import java.util.List; +import java.util.stream.Collectors; + +import static org.hamcrest.CoreMatchers.everyItem; +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.Mockito.when; +import static org.onap.vid.utils.Unchecked.toURI; + + +public class ServiceInstanceStandardQueryTest { + private static final Logger logger = LogManager.getLogger(ServiceInstanceStandardQueryTest.class); + private static final ObjectMapper MAPPER = new ObjectMapper(); + private final String serviceInstanceId = "9cdd1b2a-43a7-47bc-a88e-759ba2399f0b"; + private final String vnfInstanceId_1 = "c015cc0f-0f37-4488-aabf-53795fd93cd3"; + private final String vnfInstanceId_2 = "0846287b-65bf-45a6-88f6-6a1af4149fac"; + private final String networkInstanceId_1 = "7989a6d2-ba10-4a5d-8f15-4520bc833090"; + private final String networkInstanceId_2 = "82373aaa-c561-4e2b-96f1-7ef6f7f7b0e9"; + private final String vlanTagInstanceId_1 = "701edbb2-37e4-4473-a2a6-405cb3ab2e37"; + private final String vlanTagInstanceId_2 = "531571f4-e133-4780-8ba8-d79e63804084"; + private final String vlanTagInstanceId_3 = "df674e8c-1773-4d39-a9e9-bddd2b339d0a"; + private final String SERVICE_TYPE = "service"; + private final String VNF_TYPE = "vnf"; + + @Mock + AaiClientInterface aaiClient; + @InjectMocks + private ServiceInstanceStandardQuery serviceInstanceStandardQuery; + + @BeforeMethod + public void initMocks() { + MockitoAnnotations.initMocks(this); + + when(aaiClient.typedAaiGet(any(URI.class), any(Class.class))) + .thenAnswer(invocationOnMock -> { + final URI uri = (URI) invocationOnMock.getArguments()[0]; + final String lastPart = uri.toString().replaceAll(".*/", ""); + switch (lastPart) { + case serviceInstanceId: + return getAaiObject(ServiceInstance.class); + case vnfInstanceId_1: + case vnfInstanceId_2: + return getAaiObject(Vnf.class); + case networkInstanceId_1: + case networkInstanceId_2: + return getAaiObject(Network.class); + case vlanTagInstanceId_1: + case vlanTagInstanceId_2: + case vlanTagInstanceId_3: + return getAaiObject(Vlan.class); + default: + throw new ExceptionWithRequestInfo(HttpMethod.GET, uri.toASCIIString(), getAaiObjectString(true), 404, + new HttpClientErrorException(HttpStatus.NOT_FOUND)); + } + }); + } + + @Test + public void pathToObject_serviceInstanceUri_yieldsAaiObject() { + final ServiceInstance serviceInstance = serviceInstanceStandardQuery.objectByUri(ServiceInstance.class, toURI("/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/" + serviceInstanceId)); + assertThat(serviceInstance.getServiceInstanceId(), is(serviceInstanceId)); + assertThat(serviceInstance.getServiceInstanceName(), is("Network_repl_vMOG_rk")); + } + + @Test + public void pathToObject_networkUri_yieldsAaiObject() { + final Network network = serviceInstanceStandardQuery.objectByUri(Network.class, toURI("/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_1 + "")); + assertThat(network.getNetworkId(), is(networkInstanceId_1)); + assertThat(network.getNetworkName(), is("APPC-24595-T-IST-02AShared_cor_direct_net_1")); + } + + @Test + public void pathToObject_vlanTagUri_yieldsAaiObject() { + final Vlan vlan = serviceInstanceStandardQuery.objectByUri(Vlan.class, toURI("/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_1 + "")); + assertThat(vlan.getVlanInterface(), is("US-10688-genvnf-vlan-interface1")); + assertThat(vlan.getVlanIdInner(), is("917")); + } + + @Test(expectedExceptions = Exception.class) + public void pathToObject_oneUnknownUri_throwsException() { + serviceInstanceStandardQuery.objectByUri(ServiceInstance.class, toURI("/aai/v12/non existing path")); + } + + @Test + public void vnfsForServiceInstance_noRelatedButManyOthers_emptyResult() { + final Multival vnfs = + serviceInstanceStandardQuery.fetchRelatedVnfs(getAaiObject(false, ServiceInstance.class)); + assertThat(vnfs.getValues(), is(empty())); + } + + @Test + public void vnfsForServiceInstance_2RelatedAndManyOthers_Result2CorrectPath2() { + final Multival vnfs = + serviceInstanceStandardQuery.fetchRelatedVnfs(getAaiObject(ServiceInstance.class)); + + assertThat(vnfs.getValues(), hasSize(2)); + } + + @Test + public void serviceInstanceToL3Networks_noRelatedButManyOthers_emptyResult() { + final Multival l3Networks = + serviceInstanceStandardQuery.fetchRelatedL3Networks(SERVICE_TYPE, getAaiObject(false, ServiceInstance.class)); + assertThat(l3Networks.getValues(), is(empty())); + } + + @Test + public void serviceInstanceToL3Networks_2RelatedAndManyOthers_Result2CorrectPath2() { + final Multival l3Networks = + serviceInstanceStandardQuery.fetchRelatedL3Networks(SERVICE_TYPE, getAaiObject(ServiceInstance.class)); + + assertThat(l3Networks.getValues(), hasSize(2)); + } + + @Test + public void l3NetworkToVlanTags_noRelatedButManyOthers_emptyResult() { + final Multival vlanTags = + serviceInstanceStandardQuery.fetchRelatedVlanTags(getAaiObject(false, Network.class)); + assertThat(vlanTags.getValues(), is(empty())); + } + + @Test + public void l3NetworkToVlanTags__2RelatedAndManyOthers_Result2CorrectPath() { + final Multival vlanTags = + serviceInstanceStandardQuery.fetchRelatedVlanTags(getAaiObject(Network.class)); + + assertThat(vlanTags.getValues(), hasSize(3)); + } + + private T getAaiObject(Class valueType) { + return getAaiObject(true, valueType); + } + + private T getAaiObject(boolean withRelated, Class valueType) { + try { + return MAPPER.readValue(getAaiObjectString(withRelated), valueType); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Test + public void integrativeUsageWithLinearInvocation() throws JsonProcessingException { + final ServiceInstanceStandardQuery srv = this.serviceInstanceStandardQuery; + final ServiceInstance service = srv.fetchServiceInstance(toURI("path of service/" + serviceInstanceId + "")); + final Network l3Network = ImmutableList.copyOf(srv.fetchRelatedL3Networks(SERVICE_TYPE, service).getValues()).get(0); + final Vlan vlanTag = ImmutableList.copyOf(srv.fetchRelatedVlanTags(l3Network).getValues()).get(0); + + assertThat(vlanTag.getVlanInterface(), is("US-10688-genvnf-vlan-interface1")); + assertThat(vlanTag.getVlanIdInner(), is("917")); + } + + @Test + public void integrativeUsageWithGenericAccessors() throws JsonProcessingException { + final ServiceInstanceStandardQuery srv = this.serviceInstanceStandardQuery; + + final ServiceInstance serviceInstance = srv.fetchServiceInstance(toURI("path of service/" + serviceInstanceId + "")); + + final Multival serviceToNetworks = + srv.fetchRelatedL3Networks(SERVICE_TYPE, serviceInstance); + + final Multival> serviceToNetworksToVlans = + serviceToNetworks.mapEachVal(srv::fetchRelatedVlanTags); + + logger.info(MAPPER.writeValueAsString(serviceToNetworksToVlans)); + + // check all tags are in place + final List vlanTags = serviceToNetworksToVlans + .getValues().stream() + .flatMap(networkVlanMultival -> networkVlanMultival.getValues().stream()) + .collect(Collectors.toList()); + + assertThat(vlanTags, hasSize(6)); // 2 networks, with 3 vlans each + assertThat(vlanTags, everyItem(hasProperty("vlanInterface", is("US-10688-genvnf-vlan-interface1")))); + assertThat(vlanTags, everyItem(hasProperty("vlanIdInner", is("917")))); + } + + private String getAaiObjectString(boolean withRelated) { + final String relatedToVnfs = "" + + " { " + + " \"related-to\": \"generic-vnf\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/generic-vnfs/generic-vnf/" + vnfInstanceId_1 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"generic-vnf.vnf-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_1 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"generic-vnf.vnf-name\", " + + " \"property-value\": \"\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"generic-vnf\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/generic-vnfs/generic-vnf/" + vnfInstanceId_2 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"generic-vnf.vnf-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_2 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"generic-vnf.vnf-name\", " + + " \"property-value\": \"\" " + + " } " + + " ] " + + " }, "; + + + final String relatedToL3Networks = "" + + " { " + + " \"related-to\": \"l3-network\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_1 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"l3-network.network-id\", " + + " \"relationship-value\": \"" + networkInstanceId_1 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"l3-network.network-name\", " + + " \"property-value\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"l3-network\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/network/l3-networks/l3-network/" + networkInstanceId_2 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"l3-network.network-id\", " + + " \"relationship-value\": \"" + networkInstanceId_2 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"l3-network.network-name\", " + + " \"property-value\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\" " + + " } " + + " ] " + + " }, "; + + final String relatedToVlanTags = "" + + " { " + + " \"related-to\": \"vlan-tag\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_2 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"vlan-tag.vlan-tag-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_2 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"vlan-tag.vlan-tag-name\", " + + " \"property-value\": \"Behram_smeralda_56\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"vlan-tag\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_3 + "\" " + + " }, { " + + " \"related-to\": \"vlan-tag\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/this is an invented link/aai/v12/tag/vlan-tags/vlan-tag/" + vlanTagInstanceId_1 + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"vlan-tag.vlan-tag-id\", " + + " \"relationship-value\": \"" + vlanTagInstanceId_1 + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"vlan-tag.vlan-tag-name\", " + + " \"property-value\": \"Alexandra_Liron_3\" " + + " } " + + " ] " + + " }, "; + + return "" + + "{ " + + + // vlan props + " \"vlan-interface\": \"US-10688-genvnf-vlan-interface1\", " + + " \"vlan-id-inner\": 917, " + + " \"resource-version\": \"1518934744675\", " + + " \"in-maint\": false, " + + " \"is-ip-unnumbered\": false, " + + // imaginary vlan props + " \"vlan-tag-id\": \"" + vlanTagInstanceId_2 + "\", " + + " \"vlan-tag-name\": \"Alexandra_Liron_3\", " + + " \"vlan-tag-type\": \"SUNIWOBA\", " + + + // service-instance props + " \"service-instance-name\": \"Network_repl_vMOG_rk\", " + + " \"service-instance-id\": \"" + serviceInstanceId + "\", " + + " \"environment-context\": \"General_Revenue-Bearing\", " + + " \"workload-context\": \"Production\", " + + " \"model-invariant-id\": \"92a72881-0a97-4d16-8c29-4831062e7e9b\", " + + " \"model-version-id\": \"5a3ad576-c01d-4bed-8194-0e72b4a3d020\", " + + " \"resource-version\": \"1516045827731\", " + + " \"orchestration-status\": \"Active\", " + + + // network props + " \"network-id\": \"" + networkInstanceId_1 + "\", " + + " \"network-name\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1\", " + + " \"network-type\": \"CONTRAIL30_BASIC\", " + + " \"network-role\": \"repl\", " + + " \"network-technology\": \"contrail\", " + + " \"neutron-network-id\": \"66ee6123-1c45-4e71-b6c0-a748ae0fee88\", " + + " \"is-bound-to-vpn\": true, " + + " \"service-id\": \"db171b8f-115c-4992-a2e3-ee04cae357e0\", " + + " \"network-role-instance\": 0, " + + " \"resource-version\": \"1516046029762\", " + + " \"heat-stack-id\": \"APPC-24595-T-IST-02AShared_cor_direct_net_1/e8b256aa-8ce1-4384-9d99-6606eaca9eac\", " + + " \"contrail-network-fqdn\": \"default-domain:APPC-24595-T-IST-02C:APPC-24595-T-IST-02AShared_cor_direct_net_1\", " + + " \"physical-network-name\": \"FALSE\", " + + " \"is-provider-network\": false, " + + " \"is-shared-network\": true, " + + " \"is-external-network\": true, " + + + " \"relationship-list\": { " + + " \"relationship\": [{ " + + " \"related-to\": \"service-instance\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.ComposedOf\", " + + " \"related-link\": \"/aai/v12/business/customers/customer/a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb/service-subscriptions/service-subscription/vMOG/service-instances/service-instance/" + serviceInstanceId + "\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"customer.global-customer-id\", " + + " \"relationship-value\": \"a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb\" " + + " }, { " + + " \"relationship-key\": \"service-subscription.service-type\", " + + " \"relationship-value\": \"vMOG\" " + + " }, { " + + " \"relationship-key\": \"service-instance.service-instance-id\", " + + " \"relationship-value\": \"" + serviceInstanceId + "\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"service-instance.service-instance-name\", " + + " \"property-value\": \"Network_repl_vMOG_rk\" " + + " } " + + " ] " + + " }, { " + + " \"related-to\": \"vpn-binding\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\", " + + " \"related-link\": \"/aai/v12/network/vpn-bindings/vpn-binding/13e94b71-3ce1-4988-ab0e-61208fc91f1c\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"vpn-binding.vpn-id\", " + + " \"relationship-value\": \"13e94b71-3ce1-4988-ab0e-61208fc91f1c\" " + + " } " + + " ], " + + " \"related-to-property\": [{ " + + " \"property-key\": \"vpn-binding.vpn-name\", " + + " \"property-value\": \"vMDNS\" " + + " }, { " + + " \"property-key\": \"vpn-binding.vpn-type\" " + + " } " + + " ] " + + " }, " + (withRelated ? relatedToVlanTags : "") + "{ " + + " \"related-to\": \"project\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\", " + + " \"related-link\": \"/aai/v12/business/projects/project/project1\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"project.project-name\", " + + " \"relationship-value\": \"project1\" " + + " } " + + " ] " + + " }, " + (withRelated ? relatedToL3Networks + relatedToVnfs : "") + "{ " + + " \"related-to\": \"owning-entity\", " + + " \"relationship-label\": \"org.onap.relationships.inventory.BelongsTo\", " + + " \"related-link\": \"/aai/v12/business/owning-entities/owning-entity/589fe0db-26c4-45e5-9f4e-a246c74fce76\", " + + " \"relationship-data\": [{ " + + " \"relationship-key\": \"owning-entity.owning-entity-id\", " + + " \"relationship-value\": \"589fe0db-26c4-45e5-9f4e-a246c74fce76\" " + + " } " + + " ] " + + " } " + + " ] " + + " } " + + "} "; + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java index 7fad9019c..b5f8ff942 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/SingleAAIRestInterfaceTest.java @@ -26,7 +26,11 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; +import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.aai.exceptions.InvalidPropertyException; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.utils.Unchecked; +import org.springframework.http.HttpMethod; import org.testng.Assert; import javax.servlet.http.HttpServletRequest; @@ -37,10 +41,14 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; +import java.net.URI; import java.util.Optional; import java.util.UUID; import static javax.ws.rs.core.Response.Status.*; +import static junit.framework.TestCase.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -56,6 +64,8 @@ public class SingleAAIRestInterfaceTest { @Mock private Invocation.Builder builder; @Mock + private Invocation invocation; + @Mock private ServletRequestHelper servletRequestHelper; @Mock private HttpsAuthClient httpsAuthClient; @@ -76,6 +86,9 @@ public class SingleAAIRestInterfaceTest { when(webTarget.request()).thenReturn(builder); when(builder.accept(Mockito.anyString())).thenReturn(builder); when(builder.header(Mockito.anyString(), Mockito.anyString())).thenReturn(builder); + when(builder.build(Mockito.anyString())).thenReturn(invocation); + when(builder.build(Mockito.anyString(), any(Entity.class))).thenReturn(invocation); + when(invocation.invoke()).thenReturn(response); when(servletRequestHelper.extractOrGenerateRequestId()).thenReturn(UUID.randomUUID().toString()); } @@ -90,70 +103,67 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testSetRestSrvrBaseURLWithNullValue() throws Exception { + public void testSetRestSrvrBaseURLWithNullValue() { testSubject.SetRestSrvrBaseURL(null); } @Test - public void testSetRestSrvrBaseURL() throws Exception { + public void testSetRestSrvrBaseURL() { String baseUrl = "anything"; testSubject.SetRestSrvrBaseURL(baseUrl); Assert.assertEquals(testSubject.getRestSrvrBaseURL(), baseUrl); } @Test - public void testRestJsonPutWithResponse200() throws Exception { + public void testRestJsonPutWithResponse200() { // given String methodName = "RestPut"; String payload = "{\"id\": 1}"; Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); // when - when(builder.put(Mockito.any(Entity.class))).thenReturn(response); when(response.getStatusInfo()).thenReturn(OK); - Response finalResponse = testSubject.RestPut("", PATH, payload, false); + Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse(); // then - verify(builder).put(entity); + verify(builder).build(HttpMethod.PUT.name(), entity); Assert.assertEquals(response, finalResponse); } - @Test - public void testFailedRestJsonPut() throws Exception { + @Test(expected = ExceptionWithRequestInfo.class) + public void testFailedRestJsonPut() { // given String methodName = "RestPut"; String payload = "{\"id\": 1}"; Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); // when - when(builder.put(Mockito.any(Entity.class))).thenThrow(new RuntimeException()); - Response finalResponse = testSubject.RestPut("", PATH, payload, false); + when(builder.build(eq(HttpMethod.PUT.name()), any(Entity.class))).thenThrow(new GenericUncheckedException("msg")); + Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse(); // then - verify(builder).put(entity); - Assert.assertEquals(finalResponse, null); + fail("expected unreachable: exception to be thrown"); } @Test - public void testRestJsonPutWithResponse400() throws Exception { + public void testRestJsonPutWithResponse400() { // given String methodName = "RestPut"; String payload = "{\"id\": 1}"; Entity entity = Entity.entity(payload, MediaType.APPLICATION_JSON); // when - when(builder.put(Mockito.any(Entity.class))).thenReturn(response); when(response.getStatusInfo()).thenReturn(BAD_REQUEST); when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode()); - Response finalResponse = testSubject.RestPut("", PATH, payload, false); + Response finalResponse = testSubject.RestPut("", PATH, payload, false, true).getResponse(); // then - verify(builder).put(entity); + verify(builder).build(HttpMethod.PUT.name(), entity); Assert.assertEquals(response, finalResponse); } @Test - public void testRestPostWithResponse200() throws Exception { + public void testRestPostWithResponse200() { // given String methodName = "RestPost"; String payload = "{\"id\": 1}"; @@ -170,7 +180,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestPostWithResponse400() throws Exception { + public void testRestPostWithResponse400() { // given String methodName = "RestPost"; String payload = "{\"id\": 1}"; @@ -188,7 +198,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testFailedRestPost() throws Exception { + public void testFailedRestPost() { // given String methodName = "RestPost"; String payload = "{\"id\": 1}"; @@ -204,7 +214,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestDeleteWithResponse400() throws Exception { + public void testRestDeleteWithResponse400() { // given String methodName = "Delete"; @@ -222,7 +232,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestDeleteWithResponse404() throws Exception { + public void testRestDeleteWithResponse404() { // given String methodName = "Delete"; @@ -240,7 +250,7 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testFailedRestDelete() throws Exception { + public void testFailedRestDelete() { // given String methodName = "Delete"; @@ -254,54 +264,49 @@ public class SingleAAIRestInterfaceTest { } @Test - public void testRestJsonGetWithResponse200() throws Exception { + public void testRestJsonGetWithResponse200() { // given String methodName = "RestGet"; // when - when(builder.get()).thenReturn(response); when(response.getStatusInfo()).thenReturn(OK); - Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse(); + Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse(); // then Assert.assertEquals(response, finalResponse); } @Test - public void testRestJsonGetWithResponse400() throws Exception { + public void testRestJsonGetWithResponse400() { // given String methodName = "RestGet"; // when - when(builder.get()).thenReturn(response); when(response.getStatusInfo()).thenReturn(BAD_REQUEST); when(response.getStatus()).thenReturn(BAD_REQUEST.getStatusCode()); - Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse(); + Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse(); // then Assert.assertEquals(response, finalResponse); } @Test - public void testFailedRestGet() throws Exception { + public void testFailedRestGet() { // given String methodName = "RestGet"; // when - when(builder.get()).thenThrow(new RuntimeException()); - Response finalResponse = testSubject.RestGet("", "", PATH, false).getResponse(); + when(builder.build(HttpMethod.GET.name())).thenThrow(new RuntimeException()); + Response finalResponse = testSubject.RestGet("", "", Unchecked.toURI(PATH), false).getResponse(); // then Assert.assertEquals(finalResponse, null); } private void mockSystemProperties() throws UnsupportedEncodingException, InvalidPropertyException { - when(systemPropertyHelper.getAAIServerUrl()).thenReturn(Optional.of(HTTP_LOCALHOST)); - when(systemPropertyHelper.getAAIUseClientCert()).thenReturn(Optional.of("cert")); - when(systemPropertyHelper.getAAIVIDPasswd()).thenReturn(Optional.of("passwd")); - when(systemPropertyHelper.getAAIVIDUsername()).thenReturn(Optional.of("user")); when(systemPropertyHelper.getEncodedCredentials()).thenReturn("someCredentials"); when(systemPropertyHelper.getFullServicePath(Mockito.anyString())).thenReturn("http://localhost/path"); + when(systemPropertyHelper.getFullServicePath(Mockito.any(URI.class))).thenReturn("http://localhost/path"); when(systemPropertyHelper.getServiceBasePath(Mockito.anyString())).thenReturn("http://localhost/path"); } -- cgit 1.2.3-korg