2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 - 2019 Nokia Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.vid.asdc.rest;
24 import static org.hamcrest.CoreMatchers.containsString;
25 import static org.hamcrest.CoreMatchers.instanceOf;
26 import static org.hamcrest.CoreMatchers.notNullValue;
27 import static org.hamcrest.MatcherAssert.assertThat;
28 import static org.hamcrest.core.Is.is;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.ArgumentMatchers.anyMap;
31 import static org.mockito.ArgumentMatchers.anyString;
32 import static org.mockito.ArgumentMatchers.contains;
33 import static org.mockito.ArgumentMatchers.eq;
34 import static org.mockito.ArgumentMatchers.matches;
35 import static org.mockito.Mockito.mock;
36 import static org.mockito.Mockito.when;
37 import static org.onap.vid.testUtils.TestUtils.mockGetRawBodyWithStringBody;
38 import static org.testng.AssertJUnit.fail;
40 import io.joshworks.restclient.http.HttpResponse;
41 import java.io.InputStream;
42 import java.nio.file.Path;
43 import java.util.Collections;
44 import java.util.UUID;
45 import java.util.function.Consumer;
46 import javax.ws.rs.NotFoundException;
47 import javax.ws.rs.ProcessingException;
48 import org.apache.commons.lang3.exception.ExceptionUtils;
49 import org.mockito.Mock;
50 import org.mockito.MockitoAnnotations;
51 import org.onap.vid.asdc.AsdcCatalogException;
52 import org.onap.vid.asdc.AsdcClient;
53 import org.onap.vid.asdc.beans.Service;
54 import org.onap.vid.client.SyncRestClient;
55 import org.onap.vid.utils.Logging;
56 import org.testng.annotations.BeforeClass;
57 import org.testng.annotations.DataProvider;
58 import org.testng.annotations.Test;
60 public class SdcRestClientTest {
62 private static final String SAMPLE_SERVICE_NAME = "sampleService";
63 private static final String SAMPLE_BASE_URL = "baseUrl";
64 private static final String SAMPLE_AUTH = "sampleAuth";
65 private static final String METADATA_URL_REGEX = ".*sdc/v1/catalog/services/%s/metadata";
66 private static final String MODEL_URL_REGEX = ".*sdc/v1/catalog/services/%s/toscaModel";
70 private SyncRestClient mockedSyncRestClient;
73 private HttpResponse<Object> httpResponse;
76 private HttpResponse<InputStream> httpStreamResponse;
79 private HttpResponse<String> httpStringResponse;
82 private InputStream inputStream;
85 private Logging loggingService;
87 private UUID randomId;
89 private Service sampleService;
91 private SdcRestClient restClient;
96 MockitoAnnotations.initMocks(this);
97 randomId = UUID.randomUUID();
98 sampleService = createTestService();
99 restClient = new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, mockedSyncRestClient, loggingService);
104 public void shouldReturnServiceForGivenUUID() throws AsdcCatalogException {
105 String url = String.format(METADATA_URL_REGEX, randomId);
106 when(mockedSyncRestClient.get(matches(url), anyMap(), anyMap(), any())).thenReturn(httpResponse);
107 when(httpResponse.getBody()).thenReturn(sampleService);
109 Service service = restClient.getService(randomId);
112 assertThat(service, is(sampleService));
115 @Test( expectedExceptions = AsdcCatalogException.class)
116 public void shouldRaiseAsdcExceptionWhenClientFails() throws AsdcCatalogException {
117 String url = String.format(METADATA_URL_REGEX, randomId);
118 when(mockedSyncRestClient.get(matches(url), anyMap(), anyMap(), any())).thenThrow(new RuntimeException());
120 restClient.getService(randomId);
125 public void shouldProperlyDownloadAndCopyToscaArtifact() throws AsdcCatalogException {
126 String url = String.format(MODEL_URL_REGEX, randomId);
127 when(mockedSyncRestClient.getStream(matches(url), any(), any())).thenReturn(httpStreamResponse);
128 when(httpStreamResponse.getBody()).thenReturn(inputStream);
131 Path serviceToscaModel = restClient.getServiceToscaModel(randomId);
134 assertThat(serviceToscaModel, notNullValue());
135 assertThat(serviceToscaModel.toFile().isFile(), is(true));
137 serviceToscaModel.toFile().deleteOnExit();
140 @Test(expectedExceptions = AsdcCatalogException.class)
141 public void shouldRaiseAsdcExceptionWhenDownloadFails() throws AsdcCatalogException {
142 String url = String.format(MODEL_URL_REGEX, randomId);
143 when(mockedSyncRestClient.getStream(matches(url), anyMap(), anyMap())).thenThrow(new RuntimeException());
146 restClient.getServiceToscaModel(randomId);
150 public void shouldCallSDCHealthCheck() {
151 when(mockedSyncRestClient.get(contains(AsdcClient.URIS.HEALTH_CHECK_ENDPOINT), anyMap(),
152 eq(Collections.emptyMap()), eq(String.class))).thenReturn(httpStringResponse);
155 HttpResponse<String> stringHttpResponse = restClient.checkSDCConnectivity();
157 assertThat(httpStringResponse, is(stringHttpResponse));
160 private Service createTestService() {
161 Service service = new Service();
162 service.setInvariantUUID(randomId.toString());
163 service.setUuid(randomId.toString());
164 service.setName(SAMPLE_SERVICE_NAME);
169 public static Object[][] javaxExceptions() {
171 return new Object[][] {
172 {NotFoundException.class, (Consumer<SyncRestClient>) restClient ->
173 when(restClient.getStream(anyString(), anyMap(), anyMap())).thenThrow(
174 new NotFoundException("HTTP 404 Not Found"))
176 {ProcessingException.class, (Consumer<SyncRestClient>) restClient ->
177 when(restClient.getStream(anyString(), anyMap(), anyMap())).thenThrow(
178 new ProcessingException("java.net.ConnectException: Connection refused: connect"))},
183 @Test(dataProvider = "javaxExceptions")
184 public void whenJavaxClientThrowException_then_getServiceToscaModelRethrowException(Class<? extends Throwable> expectedType, Consumer<SyncRestClient> setupMocks) throws Exception {
187 this test -> SdcRestClient -> SdcRestClient -> joshworks client which return joshworks HttpResponse
189 In this test, *SdcRestClient* is under test (actual implementation is used), while SdcRestClient is
190 mocked to return pseudo joshworks HttpResponse or - better - throw exceptions.
194 SyncRestClient syncRestClient = mock(SyncRestClient.class);
195 setupMocks.accept(syncRestClient);
198 new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, syncRestClient, loggingService).getServiceToscaModel(UUID.randomUUID());
199 } catch (Exception e) {
200 assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType));
204 fail("exception shall rethrown by getServiceToscaModel once javax client throw exception ");
208 public static Object[][] badResponses() {
209 return new Object[][] {
210 {(Consumer<HttpResponse>) response -> {
211 when(response.getStatus()).thenReturn(404);
212 mockGetRawBodyWithStringBody(response,"");},
215 {(Consumer<HttpResponse>) response -> {
216 when(response.getStatus()).thenReturn(405);
217 when(response.getRawBody()).thenThrow(ClassCastException.class);},
220 {(Consumer<HttpResponse>) response -> {
221 when(response.getStatus()).thenReturn(500);
222 mockGetRawBodyWithStringBody(response,"some message");},
228 @Test(dataProvider = "badResponses")
229 public void whenJavaxClientReturnBadCode_then_getServiceToscaModelThrowException(Consumer<HttpResponse> setupMocks, String exceptedBody) throws Exception {
232 this test -> SdcRestClient -> SdcRestClient -> joshworks client which return joshworks HttpResponse
234 In this test, *SdcRestClient* is under test (actual implementation is used), while SdcRestClient is
235 mocked to return pseudo joshworks HttpResponse
238 HttpResponse<InputStream> mockResponse = mock(HttpResponse.class);
239 SyncRestClient syncRestClient = mock(SyncRestClient.class);
240 when(syncRestClient.getStream(anyString(), anyMap(), anyMap())).thenReturn(mockResponse);
242 // prepare real RestfulAsdcClient (Under test)
244 setupMocks.accept(mockResponse);
247 new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, syncRestClient, loggingService).getServiceToscaModel(UUID.randomUUID());
248 } catch (AsdcCatalogException e) {
249 assertThat(e.getMessage(), containsString(String.valueOf(mockResponse.getStatus())));
250 assertThat(e.getMessage(), containsString(exceptedBody));
254 fail("exception shall be thrown by getServiceToscaModel once response contains error code ");