2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.vid.services;
23 import static java.util.stream.Collectors.toMap;
24 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
25 import static org.hamcrest.CoreMatchers.containsString;
26 import static org.hamcrest.CoreMatchers.equalTo;
27 import static org.hamcrest.CoreMatchers.instanceOf;
28 import static org.hamcrest.CoreMatchers.is;
29 import static org.hamcrest.Matchers.not;
30 import static org.hamcrest.Matchers.nullValue;
31 import static org.hamcrest.core.IsSame.sameInstance;
32 import static org.junit.Assert.assertThat;
33 import static org.mockito.ArgumentMatchers.eq;
34 import static org.mockito.Mockito.any;
35 import static org.mockito.Mockito.mock;
36 import static org.mockito.Mockito.times;
37 import static org.mockito.Mockito.verify;
38 import static org.mockito.Mockito.when;
39 import static org.testng.AssertJUnit.assertTrue;
41 import com.google.common.collect.ImmutableList;
42 import com.google.common.collect.ImmutableMap;
43 import io.joshworks.restclient.http.HttpResponse;
44 import java.io.ByteArrayInputStream;
45 import java.io.InputStream;
47 import java.util.UUID;
48 import java.util.function.BiConsumer;
49 import java.util.function.Consumer;
50 import java.util.stream.Collectors;
51 import java.util.stream.Stream;
52 import javax.ws.rs.ProcessingException;
53 import org.apache.commons.lang3.RandomUtils;
54 import org.apache.commons.lang3.reflect.FieldUtils;
55 import org.apache.commons.lang3.tuple.Triple;
56 import org.mockito.Answers;
57 import org.mockito.Mock;
58 import org.mockito.MockitoAnnotations;
59 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
60 import org.onap.vid.aai.ExceptionWithRequestInfo;
61 import org.onap.vid.aai.HttpResponseWithRequestInfo;
62 import org.onap.vid.asdc.AsdcCatalogException;
63 import org.onap.vid.asdc.AsdcClient;
64 import org.onap.vid.asdc.beans.Service;
65 import org.onap.vid.asdc.parser.ToscaParserImpl2;
66 import org.onap.vid.model.ServiceModel;
67 import org.onap.vid.model.probes.ExternalComponentStatus;
68 import org.onap.vid.model.probes.HttpRequestMetadata;
69 import org.onap.vid.properties.Features;
70 import org.onap.vid.testUtils.TestUtils;
71 import org.springframework.http.HttpMethod;
72 import org.testng.annotations.BeforeMethod;
73 import org.testng.annotations.DataProvider;
74 import org.testng.annotations.Test;
75 import org.togglz.core.manager.FeatureManager;
77 public class VidServiceImplTest {
79 @Mock(answer = Answers.RETURNS_MOCKS)
80 private AsdcClient asdcClientMock;
82 @Mock(answer = Answers.RETURNS_MOCKS)
83 private ToscaParserImpl2 toscaParserMock;
86 private FeatureManager featureManager;
89 private HttpResponse<String> httpResponse;
91 private final UUID uuid1 = UUID.randomUUID();
92 private final UUID uuid2 = UUID.randomUUID();
93 private final UUID uuid3 = UUID.randomUUID();
94 private final Map<UUID, Service> pseudoServiceByUuid = ImmutableMap.of(
95 uuid1, mock(Service.class),
96 uuid2, mock(Service.class),
97 uuid3, mock(Service.class)
100 private final Map<Service, ServiceModel> pseudoModelByService =
101 pseudoServiceByUuid.values().stream()
102 .collect(toMap(service -> service, service -> mock(ServiceModel.class)));
103 private VidServiceImpl vidService;
105 private ServiceModel expectedServiceModelForUuid(UUID uuid) {
106 final ServiceModel serviceModel = pseudoModelByService.get(pseudoServiceByUuid.get(uuid));
107 assertThat(serviceModel, is(not(nullValue())));
112 public void initMocks() throws AsdcCatalogException, SdcToscaParserException, IllegalAccessException {
113 MockitoAnnotations.initMocks(this);
115 vidService = new VidServiceImpl(asdcClientMock, toscaParserMock, featureManager);
116 FieldUtils.writeField(vidService, "toscaParser", toscaParserMock, true);
118 when(featureManager.isActive(Features.FLAG_SERVICE_MODEL_CACHE)).thenReturn(true);
120 when(asdcClientMock.getService(any())).thenAnswer(invocation -> pseudoServiceByUuid.get(invocation.getArguments()[0]));
121 when(toscaParserMock.makeServiceModel(any(), any())).thenAnswer(invocation -> pseudoModelByService.get(invocation.getArguments()[1]));
125 public void whenGetServiceMultipleTimes_asdcIsCalledOnlyOnce() throws AsdcCatalogException {
126 vidService.getService(uuid1.toString());
127 vidService.getService(uuid1.toString());
128 vidService.getService(uuid1.toString());
130 verify(asdcClientMock, times(1)).getService(uuid1);
134 public void whenGetServiceTwiceWithResetBetween_asdcIsCalledTwice() throws AsdcCatalogException {
135 vidService.getService(uuid1.toString());
136 vidService.invalidateServiceCache();
137 vidService.getService(uuid1.toString());
139 verify(asdcClientMock, times(2)).getService(uuid1);
143 public void cache_saves_service_model_correctly() throws AsdcCatalogException {
144 ServiceModel service1 = vidService.getService(uuid1.toString());
145 ServiceModel service2 = vidService.getService(uuid1.toString());
146 ServiceModel service3 = vidService.getService(uuid1.toString());
148 assertThat(service1, sameInstance(expectedServiceModelForUuid(uuid1)));
149 assertThat(service1, sameInstance(service2));
150 assertThat(service1, sameInstance(service3));
154 public void cache_provide_correct_serviceModel() throws AsdcCatalogException {
155 ServiceModel service2 = vidService.getService(uuid2.toString());
156 assertThat(service2, sameInstance(expectedServiceModelForUuid(uuid2)));
158 ServiceModel service3 = vidService.getService(uuid3.toString());
159 assertThat(service3, sameInstance(expectedServiceModelForUuid(uuid3)));
161 UUID nonExisting = UUID.randomUUID();
162 ServiceModel service4 = vidService.getService(nonExisting.toString());
163 assertThat(service4, is(nullValue()));
166 @Test(expectedExceptions = AsdcCatalogException.class, expectedExceptionsMessageRegExp = "someMessage")
167 public void whenAsdcClientThrowAsdcCatalogException_thenGetServiceAlsoThrowIt() throws AsdcCatalogException {
168 when(asdcClientMock.getServiceToscaModel(any())).thenThrow(new AsdcCatalogException("someMessage"));
169 vidService.getService(uuid1.toString());
173 public void shouldCheckConnectionToSdc() {
174 mockGoodSdcConnectivityResponse();
176 ExternalComponentStatus externalComponentStatus = vidService.probeComponent();
178 assertThat(externalComponentStatus.isAvailable(), is(true));
179 assertThat(externalComponentStatus.getComponent(), is(ExternalComponentStatus.Component.SDC));
180 HttpRequestMetadata metadata = (HttpRequestMetadata) externalComponentStatus.getMetadata();
181 assertThat(metadata.getRawData(), is("sampleBody"));
184 private void mockGoodSdcConnectivityResponse() {
185 when(asdcClientMock.checkSDCConnectivity()).thenReturn(httpResponse);
186 when(httpResponse.isSuccessful()).thenReturn(true);
187 when(httpResponse.getBody()).thenReturn("sampleBody");
191 public void shouldProperlyHandleNotWorkingSDCConnection(){
192 when(asdcClientMock.checkSDCConnectivity()).thenThrow(new RuntimeException("not working"));
194 ExternalComponentStatus externalComponentStatus = vidService.probeComponent();
196 assertThat(externalComponentStatus.isAvailable(), is(false));
197 assertThat(externalComponentStatus.getMetadata().getDescription(),containsString("not working"));
201 public void shouldNotProbeBySdcConnectionIfProbeUuidConfigured() throws Exception {
202 TestUtils.testWithSystemProperty(
203 "probe.sdc.model.uuid",
204 UUID.randomUUID().toString(),
206 mockGoodSdcConnectivityResponse(); //no mocking for probeSdcByGettingModel
207 ExternalComponentStatus externalComponentStatus = vidService.probeComponent();
208 assertThat(externalComponentStatus.isAvailable(), is(false));
215 public void givenProbeUUID_whenAsdcClientReturnNormal_thenProbeComponentReturnAvailableAnswer() throws Exception {
217 final UUID uuidForProbe = UUID.randomUUID();
218 final HttpResponse<InputStream> mockResponse = mock(HttpResponse.class);
219 responseSetupper(mockResponse, 200, new ByteArrayInputStream(RandomUtils.nextBytes(66000)));
220 when(asdcClientMock.getServiceInputStream(eq(uuidForProbe), eq(true))).thenReturn(
221 new HttpResponseWithRequestInfo(mockResponse, "my pretty url", HttpMethod.GET)
224 TestUtils.testWithSystemProperty(
225 "probe.sdc.model.uuid",
226 uuidForProbe.toString(),
229 ExternalComponentStatus sdcComponentStatus = vidService.probeComponent();
230 assertTrue(sdcComponentStatus.isAvailable());
231 assertThat(sdcComponentStatus.getComponent(), is(ExternalComponentStatus.Component.SDC));
232 assertThat(sdcComponentStatus.getMetadata().getDescription(), equalTo("OK"));
233 assertThat(sdcComponentStatus.getMetadata(), instanceOf(HttpRequestMetadata.class));
235 HttpRequestMetadata componentStatusMetadata = ((HttpRequestMetadata) sdcComponentStatus.getMetadata());
236 assertThat(componentStatusMetadata.getHttpMethod(), equalTo(HttpMethod.GET));
237 assertThat(componentStatusMetadata.getHttpCode(), equalTo(200));
238 assertThat(componentStatusMetadata.getUrl(), equalTo("my pretty url"));
243 private static void responseSetupper(HttpResponse<InputStream> r, Integer httpCode, InputStream body) {
244 when(r.getStatus()).thenReturn(httpCode);
245 when(r.getRawBody()).thenReturn(body);
249 public static Object[][] executionResults() {
250 final BiConsumer<AsdcClient, HttpResponse<InputStream>> defaultClientSetup = (c, r) ->
251 when(c.getServiceInputStream(any(), eq(true))).thenReturn(new HttpResponseWithRequestInfo(r, "foo url", HttpMethod.GET));
253 final ByteArrayInputStream defaultResponseBody = new ByteArrayInputStream(RandomUtils.nextBytes(200));
255 return Stream.<Triple<HttpRequestMetadata, BiConsumer<AsdcClient, HttpResponse<InputStream>>, Consumer<HttpResponse<InputStream>>>>of(
258 new HttpRequestMetadata(null, 200, null, null, "IllegalStateException", 0),
261 when(r.getStatus()).thenReturn(200);
262 when(r.getRawBody()).thenThrow(new IllegalStateException("good news for people who love bad news"));
267 new HttpRequestMetadata(null, 200, null, null, "error reading model", 0),
269 r -> responseSetupper(r, 200, new ByteArrayInputStream(new byte[0]))
273 new HttpRequestMetadata(null, 200, null, null, "NullPointerException", 0),
275 r -> responseSetupper(r, 200, null)
279 new HttpRequestMetadata(null, 0, "bar url", null, "java.net.ConnectException: Connection refused", 0),
281 when(c.getServiceInputStream(any(), eq(true))).thenThrow(new ExceptionWithRequestInfo(HttpMethod.GET, "bar url",
282 new ProcessingException("java.net.ConnectException: Connection refused: connect"))),
283 r -> responseSetupper(r, 200, defaultResponseBody)
287 new HttpRequestMetadata(null, 500, null, null, "error while retrieving model", 0),
289 r -> responseSetupper(r, 500, defaultResponseBody)
293 new HttpRequestMetadata(null, 404, null, null, "updating vid probe configuration", 0),
295 r -> responseSetupper(r, 404, defaultResponseBody)
298 ).map(t -> ImmutableList.of(t.getLeft(), t.getMiddle(), t.getRight()).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
301 @Test(dataProvider = "executionResults")
302 public void whenClientReturnWithError_thenProbeSdcByGettingModelDescribes(HttpRequestMetadata expectedMetadata,
303 BiConsumer<AsdcClient, HttpResponse<InputStream>> clientSetup,
304 Consumer<HttpResponse<InputStream>> responseSetup) {
306 final HttpResponse<InputStream> mockResponse = mock(HttpResponse.class);
307 clientSetup.accept(asdcClientMock, mockResponse);
308 responseSetup.accept(mockResponse);
310 ExternalComponentStatus sdcComponentStatus = vidService.probeSdcByGettingModel(UUID.randomUUID());
311 assertThat(sdcComponentStatus.getComponent(), is(ExternalComponentStatus.Component.SDC));
312 assertThat(sdcComponentStatus.getMetadata(), instanceOf(HttpRequestMetadata.class));
314 HttpRequestMetadata componentStatusMetadata = ((HttpRequestMetadata) sdcComponentStatus.getMetadata());
315 assertThat(componentStatusMetadata.getDescription(), containsString(defaultIfNull(expectedMetadata.getDescription(), "OK")));
316 assertThat(componentStatusMetadata.getHttpMethod(), equalTo(defaultIfNull(expectedMetadata.getHttpMethod(), HttpMethod.GET)));
317 assertThat(componentStatusMetadata.getHttpCode(), equalTo(expectedMetadata.getHttpCode()));
318 assertThat(componentStatusMetadata.getUrl(), equalTo(defaultIfNull(expectedMetadata.getUrl(), "foo url")));
320 assertThat(sdcComponentStatus.isAvailable(), is(false));