13fe761c62ca5d7f2f3cdb4d2c80ba826503947b
[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.testng.annotations.BeforeClass;
56 import org.testng.annotations.DataProvider;
57 import org.testng.annotations.Test;
58
59 public class SdcRestClientTest {
60
61     private static final String SAMPLE_SERVICE_NAME = "sampleService";
62     private static final String SAMPLE_BASE_URL = "baseUrl";
63     private static final String SAMPLE_AUTH = "sampleAuth";
64     private static final String METADATA_URL_REGEX = ".*sdc/v1/catalog/services/%s/metadata";
65     private static final String MODEL_URL_REGEX = ".*sdc/v1/catalog/services/%s/toscaModel";
66
67
68     @Mock
69     private SyncRestClient mockedSyncRestClient;
70
71     @Mock
72     private HttpResponse<Object> httpResponse;
73
74     @Mock
75     private HttpResponse<InputStream> httpStreamResponse;
76
77     @Mock
78     private HttpResponse<String> httpStringResponse;
79
80     @Mock
81     private InputStream inputStream;
82
83     private UUID randomId;
84
85     private Service sampleService;
86
87     private SdcRestClient restClient;
88
89
90     @BeforeClass
91     public void setUp() {
92         MockitoAnnotations.initMocks(this);
93         randomId = UUID.randomUUID();
94         sampleService = createTestService();
95         restClient = new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, mockedSyncRestClient);
96     }
97
98
99     @Test
100     public void shouldReturnServiceForGivenUUID() throws AsdcCatalogException {
101         String url = String.format(METADATA_URL_REGEX, randomId);
102         when(mockedSyncRestClient.get(matches(url), anyMap(), anyMap(), any())).thenReturn(httpResponse);
103         when(httpResponse.getBody()).thenReturn(sampleService);
104
105         Service service = restClient.getService(randomId);
106
107
108         assertThat(service, is(sampleService));
109     }
110
111     @Test( expectedExceptions = AsdcCatalogException.class)
112     public void shouldRaiseAsdcExceptionWhenClientFails() throws AsdcCatalogException {
113         String url = String.format(METADATA_URL_REGEX, randomId);
114         when(mockedSyncRestClient.get(matches(url), anyMap(), anyMap(), any())).thenThrow(new RuntimeException());
115
116         restClient.getService(randomId);
117     }
118
119
120     @Test
121     public void shouldProperlyDownloadAndCopyToscaArtifact() throws AsdcCatalogException {
122         String url = String.format(MODEL_URL_REGEX, randomId);
123         when(mockedSyncRestClient.getStream(matches(url), any(), any())).thenReturn(httpStreamResponse);
124         when(httpStreamResponse.getBody()).thenReturn(inputStream);
125
126
127         Path serviceToscaModel = restClient.getServiceToscaModel(randomId);
128
129
130         assertThat(serviceToscaModel, notNullValue());
131         assertThat(serviceToscaModel.toFile().isFile(), is(true));
132
133         serviceToscaModel.toFile().deleteOnExit();
134     }
135
136     @Test(expectedExceptions = AsdcCatalogException.class)
137     public void shouldRaiseAsdcExceptionWhenDownloadFails() throws AsdcCatalogException {
138         String url = String.format(MODEL_URL_REGEX, randomId);
139         when(mockedSyncRestClient.getStream(matches(url), anyMap(), anyMap())).thenThrow(new RuntimeException());
140
141
142         restClient.getServiceToscaModel(randomId);
143     }
144
145     @Test
146     public void shouldCallSDCHealthCheck() {
147         when(mockedSyncRestClient.get(contains(AsdcClient.URIS.HEALTH_CHECK_ENDPOINT), anyMap(),
148                 eq(Collections.emptyMap()), eq(String.class))).thenReturn(httpStringResponse);
149
150
151         HttpResponse<String> stringHttpResponse = restClient.checkSDCConnectivity();
152
153         assertThat(httpStringResponse, is(stringHttpResponse));
154     }
155
156     private Service createTestService() {
157         Service service = new Service();
158         service.setInvariantUUID(randomId.toString());
159         service.setUuid(randomId.toString());
160         service.setName(SAMPLE_SERVICE_NAME);
161         return service;
162     }
163
164     @DataProvider
165     public static Object[][] javaxExceptions() {
166
167         return new Object[][] {
168             {NotFoundException.class, (Consumer<SyncRestClient>) restClient ->
169                 when(restClient.getStream(anyString(), anyMap(), anyMap())).thenThrow(
170                     new NotFoundException("HTTP 404 Not Found"))
171             },
172             {ProcessingException.class, (Consumer<SyncRestClient>) restClient ->
173                 when(restClient.getStream(anyString(), anyMap(), anyMap())).thenThrow(
174                     new ProcessingException("java.net.ConnectException: Connection refused: connect"))},
175         };
176     }
177
178
179     @Test(dataProvider = "javaxExceptions")
180     public void whenJavaxClientThrowException_then_getServiceToscaModelRethrowException(Class<? extends Throwable> expectedType, Consumer<SyncRestClient> setupMocks) throws Exception {
181         /*
182         Call chain is like:
183             this test -> SdcRestClient ->  SdcRestClient -> joshworks client which return  joshworks HttpResponse
184
185         In this test, *SdcRestClient* is under test (actual implementation is used), while SdcRestClient is
186         mocked to return pseudo joshworks HttpResponse or - better - throw exceptions.
187          */
188
189         /// TEST:
190         SyncRestClient syncRestClient = mock(SyncRestClient.class);
191         setupMocks.accept(syncRestClient);
192
193         try {
194             new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, syncRestClient).getServiceToscaModel(UUID.randomUUID());
195         } catch (Exception e) {
196             assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType));
197             return; //OK
198         }
199
200         fail("exception shall rethrown by getServiceToscaModel once javax client throw exception ");
201     }
202
203     @DataProvider
204     public static Object[][] badResponses() {
205         return new Object[][] {
206             {(Consumer<HttpResponse>) response -> {
207                 when(response.getStatus()).thenReturn(404);
208                 mockGetRawBodyWithStringBody(response,"");},
209                 ""
210             },
211             {(Consumer<HttpResponse>) response -> {
212                 when(response.getStatus()).thenReturn(405);
213                 when(response.getRawBody()).thenThrow(ClassCastException.class);},
214                 ""
215             },
216             {(Consumer<HttpResponse>) response -> {
217                 when(response.getStatus()).thenReturn(500);
218                 mockGetRawBodyWithStringBody(response,"some message");},
219                 "some message"
220             },
221         };
222     }
223
224     @Test(dataProvider = "badResponses")
225     public void whenJavaxClientReturnBadCode_then_getServiceToscaModelThrowException(Consumer<HttpResponse> setupMocks, String exceptedBody) throws Exception {
226         /*
227         Call chain is like:
228             this test -> SdcRestClient ->  SdcRestClient -> joshworks client which return  joshworks HttpResponse
229
230         In this test, *SdcRestClient* is under test (actual implementation is used), while SdcRestClient is
231         mocked to return pseudo joshworks HttpResponse
232          */
233
234         HttpResponse<InputStream> mockResponse = mock(HttpResponse.class);
235         SyncRestClient syncRestClient = mock(SyncRestClient.class);
236         when(syncRestClient.getStream(anyString(), anyMap(), anyMap())).thenReturn(mockResponse);
237
238         // prepare real RestfulAsdcClient (Under test)
239
240         setupMocks.accept(mockResponse);
241
242         try {
243             new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, syncRestClient).getServiceToscaModel(UUID.randomUUID());
244         } catch (AsdcCatalogException e) {
245             assertThat(e.getMessage(), containsString(String.valueOf(mockResponse.getStatus())));
246             assertThat(e.getMessage(), containsString(exceptedBody));
247             return; //OK
248         }
249
250         fail("exception shall be thrown by getServiceToscaModel once response contains error code ");
251     }
252
253
254 }