aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test
diff options
context:
space:
mode:
Diffstat (limited to 'vid-app-common/src/test')
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java1
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/asdc/local/LocalAsdcClient.java232
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java155
3 files changed, 384 insertions, 4 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java
index b2d8e85fa..9793862ca 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
@@ -56,6 +56,7 @@ import java.net.URI;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Map;
+import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Stream;
diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/local/LocalAsdcClient.java b/vid-app-common/src/test/java/org/onap/vid/asdc/local/LocalAsdcClient.java
new file mode 100644
index 000000000..2f5853e47
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/asdc/local/LocalAsdcClient.java
@@ -0,0 +1,232 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2019 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.asdc.local;
+
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.joshworks.restclient.http.HttpResponse;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.UUID;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.vid.aai.HttpResponseWithRequestInfo;
+import org.onap.vid.asdc.AsdcCatalogException;
+import org.onap.vid.asdc.AsdcClient;
+import org.onap.vid.asdc.beans.Service;
+import org.onap.vid.exceptions.GenericUncheckedException;
+
+/**
+ * The Class LocalAsdcClient.
+ */
+public class LocalAsdcClient implements AsdcClient {
+
+
+ public static final String SERVICES = "services";
+ /**
+ * The catalog.
+ */
+ private final JSONObject catalog;
+
+ /**
+ * The mapper.
+ */
+ private final ObjectMapper mapper;
+
+ /**
+ * Instantiates a new in local sdc client.
+ *
+ * @param builder the builder
+ */
+ public LocalAsdcClient(org.onap.vid.asdc.local.LocalAsdcClient.Builder builder) {
+ catalog = builder.catalog;
+ mapper = builder.mapper;
+ }
+
+ /**
+ * Gets the catalog.
+ *
+ * @return the catalog
+ */
+ private JSONObject getCatalog() {
+ return catalog;
+ }
+
+ /**
+ * Gets the mapper.
+ *
+ * @return the mapper
+ */
+ private ObjectMapper getMapper() {
+ return mapper;
+ }
+
+ /**
+ * Convert.
+ *
+ * @param <T> the generic type
+ * @param json the json
+ * @param clazz the clazz
+ * @return the t
+ * @throws AsdcCatalogException the sdc catalog exception
+ */
+ private <T> T convert(JSONObject json, Class<T> clazz) throws AsdcCatalogException {
+ try {
+ return getMapper().readValue(json.toString(), clazz);
+ } catch (JsonParseException e) {
+ throw new AsdcCatalogException("Failed to parse SDC response (bad data)", e);
+ } catch (JsonMappingException e) {
+ throw new AsdcCatalogException("Failed to map SDC response to internal VID data structure(s)", e);
+ } catch (IOException e) {
+ throw new AsdcCatalogException("Failed to get a response from SDC", e);
+ }
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.vid.asdc.AsdcClient#getService(java.util.UUID)
+ */
+ public Service getService(UUID uuid) throws AsdcCatalogException {
+
+ JSONObject serviceJsonObject = null;
+ final JSONArray categoryJsonArray = getCatalog().getJSONArray(SERVICES);
+
+ for (int i = 0; i < categoryJsonArray.length(); i++) {
+ JSONObject jsonServiceObject = categoryJsonArray.getJSONObject(i);
+ if (jsonServiceObject.get("uuid").equals(uuid.toString())) {
+ serviceJsonObject = jsonServiceObject;
+ break;
+ }
+ }
+
+ if (serviceJsonObject != null)
+ return convert(serviceJsonObject, Service.class);
+ else return null;
+ }
+
+ /* (non-Javadoc)
+ * @see org.onap.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID)
+ */
+ public Path getServiceToscaModel(UUID serviceUuid) {
+
+ String toscaModelURL = null;
+
+ final JSONArray categoryJsonArray = getCatalog().getJSONArray(SERVICES);
+
+ for (int i = 0; i < categoryJsonArray.length(); i++) {
+
+ JSONObject jsonServiceObject = categoryJsonArray.getJSONObject(i);
+ if (jsonServiceObject.get("uuid").equals(serviceUuid.toString())) {
+ toscaModelURL = jsonServiceObject.getString("toscaModelURL");
+ }
+ }
+ if (toscaModelURL == null) {
+ return null;
+ }
+ ClassLoader classLoader = getClass().getClassLoader();
+
+ try {
+ File file = new File(classLoader.getResource(toscaModelURL).getFile());
+ //using URLDecoder.decode to convert special characters from %XX to real character
+ //see https://stackoverflow.com/questions/32251251/java-classloader-getresource-with-special-characters-in-path
+ return Paths.get(URLDecoder.decode(file.getPath(), "UTF-8"));
+ } catch (RuntimeException | UnsupportedEncodingException e) {
+ throw new GenericUncheckedException("Can't find " + toscaModelURL, e);
+ }
+ }
+
+ @Override
+ public HttpResponse<String> checkSDCConnectivity() {
+ return HttpResponse.fallback("");
+ }
+
+ @Override
+ public HttpResponseWithRequestInfo<InputStream> getServiceInputStream(UUID serviceUuid, boolean warpException) {
+ return null;
+ }
+
+ @Override
+ public String getBaseUrl(){
+ return "";
+ }
+
+ /**
+ * The Class Builder.
+ */
+ public static class Builder {
+
+ /**
+ * The catalog.
+ */
+ private JSONObject catalog = new JSONObject()
+ .put("resources", new JSONObject())
+ .put(SERVICES, new JSONObject());
+
+ /**
+ * The mapper.
+ */
+ private ObjectMapper mapper = new ObjectMapper();
+
+ /**
+ * Instantiates a new builder.
+ */
+ public Builder() {
+ }
+
+ /**
+ * Catalog.
+ *
+ * @param catalog the catalog
+ * @return the builder
+ */
+ public org.onap.vid.asdc.local.LocalAsdcClient.Builder catalog(JSONObject catalog) {
+ this.catalog = catalog;
+ return this;
+ }
+
+ /**
+ * Mapper.
+ *
+ * @param mapper the mapper
+ * @return the builder
+ */
+ public org.onap.vid.asdc.local.LocalAsdcClient.Builder mapper(ObjectMapper mapper) {
+ this.mapper = mapper;
+ return this;
+ }
+
+ /**
+ * Builds the.
+ *
+ * @return the in local sdc client
+ */
+ public org.onap.vid.asdc.local.LocalAsdcClient build() {
+ return new org.onap.vid.asdc.local.LocalAsdcClient(this);
+ }
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java
index ff6b7f0b1..65712b423 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java
@@ -21,27 +21,44 @@
package org.onap.vid.services;
import static java.util.stream.Collectors.toMap;
+import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import static org.testng.AssertJUnit.assertTrue;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.joshworks.restclient.http.HttpResponse;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
import java.util.Map;
import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.ws.rs.ProcessingException;
+import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.commons.lang3.tuple.Triple;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
+import org.onap.vid.aai.HttpResponseWithRequestInfo;
import org.onap.vid.asdc.AsdcCatalogException;
import org.onap.vid.asdc.AsdcClient;
import org.onap.vid.asdc.beans.Service;
@@ -50,7 +67,10 @@ import org.onap.vid.model.ServiceModel;
import org.onap.vid.model.probes.ExternalComponentStatus;
import org.onap.vid.model.probes.HttpRequestMetadata;
import org.onap.vid.properties.Features;
+import org.onap.vid.testUtils.TestUtils;
+import org.springframework.http.HttpMethod;
import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.togglz.core.manager.FeatureManager;
@@ -151,10 +171,7 @@ public class VidServiceImplTest {
@Test
public void shouldCheckConnectionToSdc() {
- when(asdcClientMock.checkSDCConnectivity()).thenReturn(httpResponse);
- when(httpResponse.isSuccessful()).thenReturn(true);
- when(httpResponse.getBody()).thenReturn("sampleBody");
-
+ mockGoodSdcConnectivityResponse();
ExternalComponentStatus externalComponentStatus = vidService.probeComponent();
@@ -164,6 +181,12 @@ public class VidServiceImplTest {
assertThat(metadata.getRawData(), is("sampleBody"));
}
+ private void mockGoodSdcConnectivityResponse() {
+ when(asdcClientMock.checkSDCConnectivity()).thenReturn(httpResponse);
+ when(httpResponse.isSuccessful()).thenReturn(true);
+ when(httpResponse.getBody()).thenReturn("sampleBody");
+ }
+
@Test
public void shouldProperlyHandleNotWorkingSDCConnection(){
when(asdcClientMock.checkSDCConnectivity()).thenThrow(new RuntimeException("not working"));
@@ -173,5 +196,129 @@ public class VidServiceImplTest {
assertThat(externalComponentStatus.isAvailable(), is(false));
assertThat(externalComponentStatus.getMetadata().getDescription(),containsString("not working"));
}
+
+ @Test
+ public void shouldNotProbeBySdcConnectionIfProbeUuidConfigured() throws Exception {
+ TestUtils.testWithSystemProperty(
+ "probe.sdc.model.uuid",
+ UUID.randomUUID().toString(),
+ ()->{
+ mockGoodSdcConnectivityResponse(); //no mocking for probeSdcByGettingModel
+ ExternalComponentStatus externalComponentStatus = vidService.probeComponent();
+ assertThat(externalComponentStatus.isAvailable(), is(false));
+ }
+ );
+ }
+
+
+ @Test
+ public void givenProbeUUID_whenAsdcClientReturnNormal_thenProbeComponentReturnAvailableAnswer() throws Exception {
+
+ final UUID uuidForProbe = UUID.randomUUID();
+ final HttpResponse<InputStream> mockResponse = mock(HttpResponse.class);
+ responseSetupper(mockResponse, 200, new ByteArrayInputStream(RandomUtils.nextBytes(66000)));
+ when(asdcClientMock.getServiceInputStream(eq(uuidForProbe), eq(true))).thenReturn(
+ new HttpResponseWithRequestInfo(mockResponse, "my pretty url", HttpMethod.GET)
+ );
+
+ TestUtils.testWithSystemProperty(
+ "probe.sdc.model.uuid",
+ uuidForProbe.toString(),
+ ()-> {
+
+ ExternalComponentStatus sdcComponentStatus = vidService.probeComponent();
+ assertTrue(sdcComponentStatus.isAvailable());
+ assertThat(sdcComponentStatus.getComponent(), is(ExternalComponentStatus.Component.SDC));
+ assertThat(sdcComponentStatus.getMetadata().getDescription(), equalTo("OK"));
+ assertThat(sdcComponentStatus.getMetadata(), instanceOf(HttpRequestMetadata.class));
+
+ HttpRequestMetadata componentStatusMetadata = ((HttpRequestMetadata) sdcComponentStatus.getMetadata());
+ assertThat(componentStatusMetadata.getHttpMethod(), equalTo(HttpMethod.GET));
+ assertThat(componentStatusMetadata.getHttpCode(), equalTo(200));
+ assertThat(componentStatusMetadata.getUrl(), equalTo("my pretty url"));
+ }
+ );
+ }
+
+ private static void responseSetupper(HttpResponse<InputStream> r, Integer httpCode, InputStream body) {
+ when(r.getStatus()).thenReturn(httpCode);
+ when(r.getRawBody()).thenReturn(body);
+ }
+
+ @DataProvider
+ public static Object[][] executionResults() {
+ final BiConsumer<AsdcClient, HttpResponse<InputStream>> defaultClientSetup = (c, r) ->
+ when(c.getServiceInputStream(any(), eq(true))).thenReturn(new HttpResponseWithRequestInfo(r, "foo url", HttpMethod.GET));
+
+ final ByteArrayInputStream defaultResponseBody = new ByteArrayInputStream(RandomUtils.nextBytes(200));
+
+ return Stream.<Triple<HttpRequestMetadata, BiConsumer<AsdcClient, HttpResponse<InputStream>>, Consumer<HttpResponse<InputStream>>>>of(
+
+ Triple.of(
+ new HttpRequestMetadata(null, 200, null, null, "IllegalStateException", 0),
+ defaultClientSetup,
+ r -> {
+ when(r.getStatus()).thenReturn(200);
+ when(r.getRawBody()).thenThrow(new IllegalStateException("good news for people who love bad news"));
+ }
+ ),
+
+ Triple.of(
+ new HttpRequestMetadata(null, 200, null, null, "error reading model", 0),
+ defaultClientSetup,
+ r -> responseSetupper(r, 200, new ByteArrayInputStream(new byte[0]))
+ ),
+//
+ Triple.of(
+ new HttpRequestMetadata(null, 200, null, null, "NullPointerException", 0),
+ defaultClientSetup,
+ r -> responseSetupper(r, 200, null)
+ ),
+//
+ Triple.of(
+ new HttpRequestMetadata(null, 0, "bar url", null, "java.net.ConnectException: Connection refused", 0),
+ (c, r) ->
+ when(c.getServiceInputStream(any(), eq(true))).thenThrow(new ExceptionWithRequestInfo(HttpMethod.GET, "bar url",
+ new ProcessingException("java.net.ConnectException: Connection refused: connect"))),
+ r -> responseSetupper(r, 200, defaultResponseBody)
+ ),
+
+ Triple.of(
+ new HttpRequestMetadata(null, 500, null, null, "error while retrieving model", 0),
+ defaultClientSetup,
+ r -> responseSetupper(r, 500, defaultResponseBody)
+ ),
+
+ Triple.of(
+ new HttpRequestMetadata(null, 404, null, null, "updating vid probe configuration", 0),
+ defaultClientSetup,
+ r -> responseSetupper(r, 404, defaultResponseBody)
+ )
+
+ ).map(t -> ImmutableList.of(t.getLeft(), t.getMiddle(), t.getRight()).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
+ }
+
+ @Test(dataProvider = "executionResults")
+ public void whenClientReturnWithError_thenProbeSdcByGettingModelDescribes(HttpRequestMetadata expectedMetadata,
+ BiConsumer<AsdcClient, HttpResponse<InputStream>> clientSetup,
+ Consumer<HttpResponse<InputStream>> responseSetup) {
+
+ final HttpResponse<InputStream> mockResponse = mock(HttpResponse.class);
+ clientSetup.accept(asdcClientMock, mockResponse);
+ responseSetup.accept(mockResponse);
+
+ ExternalComponentStatus sdcComponentStatus = vidService.probeSdcByGettingModel(UUID.randomUUID());
+ assertThat(sdcComponentStatus.getComponent(), is(ExternalComponentStatus.Component.SDC));
+ assertThat(sdcComponentStatus.getMetadata(), instanceOf(HttpRequestMetadata.class));
+
+ HttpRequestMetadata componentStatusMetadata = ((HttpRequestMetadata) sdcComponentStatus.getMetadata());
+ assertThat(componentStatusMetadata.getDescription(), containsString(defaultIfNull(expectedMetadata.getDescription(), "OK")));
+ assertThat(componentStatusMetadata.getHttpMethod(), equalTo(defaultIfNull(expectedMetadata.getHttpMethod(), HttpMethod.GET)));
+ assertThat(componentStatusMetadata.getHttpCode(), equalTo(expectedMetadata.getHttpCode()));
+ assertThat(componentStatusMetadata.getUrl(), equalTo(defaultIfNull(expectedMetadata.getUrl(), "foo url")));
+
+ assertThat(sdcComponentStatus.isAvailable(), is(false));
+ }
+
}