make Logging a service and inject it to SyncRestClient
[vid.git] / vid-app-common / src / test / java / org / onap / vid / asdc / rest / SdcRestClientTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
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=========================================================
20  */
21
22 package org.onap.vid.asdc.rest;
23
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;
39
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;
59
60 public class SdcRestClientTest {
61
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";
67
68
69     @Mock
70     private SyncRestClient mockedSyncRestClient;
71
72     @Mock
73     private HttpResponse<Object> httpResponse;
74
75     @Mock
76     private HttpResponse<InputStream> httpStreamResponse;
77
78     @Mock
79     private HttpResponse<String> httpStringResponse;
80
81     @Mock
82     private InputStream inputStream;
83
84     @Mock
85     private Logging loggingService;
86
87     private UUID randomId;
88
89     private Service sampleService;
90
91     private SdcRestClient restClient;
92
93
94     @BeforeClass
95     public void setUp() {
96         MockitoAnnotations.initMocks(this);
97         randomId = UUID.randomUUID();
98         sampleService = createTestService();
99         restClient = new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, mockedSyncRestClient, loggingService);
100     }
101
102
103     @Test
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);
108
109         Service service = restClient.getService(randomId);
110
111
112         assertThat(service, is(sampleService));
113     }
114
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());
119
120         restClient.getService(randomId);
121     }
122
123
124     @Test
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);
129
130
131         Path serviceToscaModel = restClient.getServiceToscaModel(randomId);
132
133
134         assertThat(serviceToscaModel, notNullValue());
135         assertThat(serviceToscaModel.toFile().isFile(), is(true));
136
137         serviceToscaModel.toFile().deleteOnExit();
138     }
139
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());
144
145
146         restClient.getServiceToscaModel(randomId);
147     }
148
149     @Test
150     public void shouldCallSDCHealthCheck() {
151         when(mockedSyncRestClient.get(contains(AsdcClient.URIS.HEALTH_CHECK_ENDPOINT), anyMap(),
152                 eq(Collections.emptyMap()), eq(String.class))).thenReturn(httpStringResponse);
153
154
155         HttpResponse<String> stringHttpResponse = restClient.checkSDCConnectivity();
156
157         assertThat(httpStringResponse, is(stringHttpResponse));
158     }
159
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);
165         return service;
166     }
167
168     @DataProvider
169     public static Object[][] javaxExceptions() {
170
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"))
175             },
176             {ProcessingException.class, (Consumer<SyncRestClient>) restClient ->
177                 when(restClient.getStream(anyString(), anyMap(), anyMap())).thenThrow(
178                     new ProcessingException("java.net.ConnectException: Connection refused: connect"))},
179         };
180     }
181
182
183     @Test(dataProvider = "javaxExceptions")
184     public void whenJavaxClientThrowException_then_getServiceToscaModelRethrowException(Class<? extends Throwable> expectedType, Consumer<SyncRestClient> setupMocks) throws Exception {
185         /*
186         Call chain is like:
187             this test -> SdcRestClient ->  SdcRestClient -> joshworks client which return  joshworks HttpResponse
188
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.
191          */
192
193         /// TEST:
194         SyncRestClient syncRestClient = mock(SyncRestClient.class);
195         setupMocks.accept(syncRestClient);
196
197         try {
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));
201             return; //OK
202         }
203
204         fail("exception shall rethrown by getServiceToscaModel once javax client throw exception ");
205     }
206
207     @DataProvider
208     public static Object[][] badResponses() {
209         return new Object[][] {
210             {(Consumer<HttpResponse>) response -> {
211                 when(response.getStatus()).thenReturn(404);
212                 mockGetRawBodyWithStringBody(response,"");},
213                 ""
214             },
215             {(Consumer<HttpResponse>) response -> {
216                 when(response.getStatus()).thenReturn(405);
217                 when(response.getRawBody()).thenThrow(ClassCastException.class);},
218                 ""
219             },
220             {(Consumer<HttpResponse>) response -> {
221                 when(response.getStatus()).thenReturn(500);
222                 mockGetRawBodyWithStringBody(response,"some message");},
223                 "some message"
224             },
225         };
226     }
227
228     @Test(dataProvider = "badResponses")
229     public void whenJavaxClientReturnBadCode_then_getServiceToscaModelThrowException(Consumer<HttpResponse> setupMocks, String exceptedBody) throws Exception {
230         /*
231         Call chain is like:
232             this test -> SdcRestClient ->  SdcRestClient -> joshworks client which return  joshworks HttpResponse
233
234         In this test, *SdcRestClient* is under test (actual implementation is used), while SdcRestClient is
235         mocked to return pseudo joshworks HttpResponse
236          */
237
238         HttpResponse<InputStream> mockResponse = mock(HttpResponse.class);
239         SyncRestClient syncRestClient = mock(SyncRestClient.class);
240         when(syncRestClient.getStream(anyString(), anyMap(), anyMap())).thenReturn(mockResponse);
241
242         // prepare real RestfulAsdcClient (Under test)
243
244         setupMocks.accept(mockResponse);
245
246         try {
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));
251             return; //OK
252         }
253
254         fail("exception shall be thrown by getServiceToscaModel once response contains error code ");
255     }
256
257
258 }