5eaaf933576770d6c7fa2abf732b56bfe3b2e375
[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.instanceOf;
25 import static org.hamcrest.CoreMatchers.notNullValue;
26 import static org.hamcrest.MatcherAssert.assertThat;
27 import static org.hamcrest.core.Is.is;
28 import static org.mockito.ArgumentMatchers.any;
29 import static org.mockito.ArgumentMatchers.anyMap;
30 import static org.mockito.ArgumentMatchers.anyString;
31 import static org.mockito.ArgumentMatchers.contains;
32 import static org.mockito.ArgumentMatchers.eq;
33 import static org.mockito.ArgumentMatchers.matches;
34 import static org.mockito.Mockito.mock;
35 import static org.mockito.Mockito.when;
36 import static org.testng.AssertJUnit.fail;
37
38 import io.joshworks.restclient.http.HttpResponse;
39 import java.io.InputStream;
40 import java.nio.file.Path;
41 import java.util.Collections;
42 import java.util.UUID;
43 import java.util.function.Consumer;
44 import javax.ws.rs.NotFoundException;
45 import javax.ws.rs.ProcessingException;
46 import org.apache.commons.lang3.exception.ExceptionUtils;
47 import org.mockito.Mock;
48 import org.mockito.MockitoAnnotations;
49 import org.onap.vid.asdc.AsdcCatalogException;
50 import org.onap.vid.asdc.AsdcClient;
51 import org.onap.vid.asdc.beans.Service;
52 import org.onap.vid.client.SyncRestClient;
53 import org.testng.annotations.BeforeClass;
54 import org.testng.annotations.DataProvider;
55 import org.testng.annotations.Test;
56
57 public class SdcRestClientTest {
58
59     private static final String SAMPLE_SERVICE_NAME = "sampleService";
60     private static final String SAMPLE_BASE_URL = "baseUrl";
61     private static final String SAMPLE_AUTH = "sampleAuth";
62     private static final String METADATA_URL_REGEX = ".*sdc/v1/catalog/services/%s/metadata";
63     private static final String MODEL_URL_REGEX = ".*sdc/v1/catalog/services/%s/toscaModel";
64
65
66     @Mock
67     private SyncRestClient mockedSyncRestClient;
68
69     @Mock
70     private HttpResponse<Object> httpResponse;
71
72     @Mock
73     private HttpResponse<InputStream> httpStreamResponse;
74
75     @Mock
76     private HttpResponse<String> httpStringResponse;
77
78     @Mock
79     private InputStream inputStream;
80
81     private UUID randomId;
82
83     private Service sampleService;
84
85     private SdcRestClient restClient;
86
87
88     @BeforeClass
89     public void setUp() {
90         MockitoAnnotations.initMocks(this);
91         randomId = UUID.randomUUID();
92         sampleService = createTestService();
93         restClient = new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, mockedSyncRestClient);
94     }
95
96
97     @Test
98     public void shouldReturnServiceForGivenUUID() throws AsdcCatalogException {
99         String url = String.format(METADATA_URL_REGEX, randomId);
100         when(mockedSyncRestClient.get(matches(url), anyMap(), anyMap(), any())).thenReturn(httpResponse);
101         when(httpResponse.getBody()).thenReturn(sampleService);
102
103         Service service = restClient.getService(randomId);
104
105
106         assertThat(service, is(sampleService));
107     }
108
109     @Test( expectedExceptions = AsdcCatalogException.class)
110     public void shouldRaiseAsdcExceptionWhenClientFails() throws AsdcCatalogException {
111         String url = String.format(METADATA_URL_REGEX, randomId);
112         when(mockedSyncRestClient.get(matches(url), anyMap(), anyMap(), any())).thenThrow(new RuntimeException());
113
114         restClient.getService(randomId);
115     }
116
117
118     @Test
119     public void shouldProperlyDownloadAndCopyToscaArtifact() throws AsdcCatalogException {
120         String url = String.format(MODEL_URL_REGEX, randomId);
121         when(mockedSyncRestClient.getStream(matches(url), any(), any())).thenReturn(httpStreamResponse);
122         when(httpStreamResponse.getBody()).thenReturn(inputStream);
123
124
125         Path serviceToscaModel = restClient.getServiceToscaModel(randomId);
126
127
128         assertThat(serviceToscaModel, notNullValue());
129         assertThat(serviceToscaModel.toFile().isFile(), is(true));
130
131         serviceToscaModel.toFile().deleteOnExit();
132     }
133
134     @Test(expectedExceptions = AsdcCatalogException.class)
135     public void shouldRaiseAsdcExceptionWhenDownloadFails() throws AsdcCatalogException {
136         String url = String.format(MODEL_URL_REGEX, randomId);
137         when(mockedSyncRestClient.getStream(matches(url), anyMap(), anyMap())).thenThrow(new RuntimeException());
138
139
140         restClient.getServiceToscaModel(randomId);
141     }
142
143     @Test
144     public void shouldCallSDCHealthCheck() {
145         when(mockedSyncRestClient.get(contains(AsdcClient.URIS.HEALTH_CHECK_ENDPOINT), anyMap(),
146                 eq(Collections.emptyMap()), eq(String.class))).thenReturn(httpStringResponse);
147
148
149         HttpResponse<String> stringHttpResponse = restClient.checkSDCConnectivity();
150
151         assertThat(httpStringResponse, is(stringHttpResponse));
152     }
153
154     private Service createTestService() {
155         Service service = new Service();
156         service.setInvariantUUID(randomId.toString());
157         service.setUuid(randomId.toString());
158         service.setName(SAMPLE_SERVICE_NAME);
159         return service;
160     }
161
162     @DataProvider
163     public static Object[][] javaxExceptions() {
164
165         return new Object[][] {
166             {NotFoundException.class, (Consumer<SyncRestClient>) restClient ->
167                 when(restClient.getStream(anyString(), anyMap(), anyMap())).thenThrow(
168                     new NotFoundException("HTTP 404 Not Found"))
169             },
170             {ProcessingException.class, (Consumer<SyncRestClient>) restClient ->
171                 when(restClient.getStream(anyString(), anyMap(), anyMap())).thenThrow(
172                     new ProcessingException("java.net.ConnectException: Connection refused: connect"))},
173         };
174     }
175
176
177     @Test(dataProvider = "javaxExceptions")
178     public void whenJavaxClientThrowException_then_getServiceToscaModelRethrowException(Class<? extends Throwable> expectedType, Consumer<SyncRestClient> setupMocks) throws Exception {
179         /*
180         Call chain is like:
181             this test -> RestfulAsdcClient ->  javax's Client
182
183         In this test, *RestfulAsdcClient* is under test (actual implementation is used), while javax's Client is
184         mocked to return pseudo-responses or - better - throw exceptions.
185          */
186
187         /// TEST:
188         SyncRestClient syncRestClient = mock(SyncRestClient.class);
189         setupMocks.accept(syncRestClient);
190
191         try {
192             new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, syncRestClient).getServiceToscaModel(UUID.randomUUID());
193         } catch (Exception e) {
194             assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType));
195             return; //OK
196         }
197
198         fail("exception shall rethrown by getServiceToscaModel once javax client throw exception ");
199     }
200
201 }