Merge "change management cypress test"
[vid.git] / vid-app-common / src / test / java / org / onap / vid / mso / rest / OutgoingRequestHeadersTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.vid.mso.rest;
22
23 import static org.apache.commons.io.IOUtils.toInputStream;
24 import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
25 import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
26 import static org.hamcrest.CoreMatchers.is;
27 import static org.hamcrest.CoreMatchers.startsWith;
28 import static org.hamcrest.MatcherAssert.assertThat;
29 import static org.hamcrest.Matchers.allOf;
30 import static org.hamcrest.Matchers.hasItem;
31 import static org.hamcrest.Matchers.hasToString;
32 import static org.hamcrest.Matchers.instanceOf;
33 import static org.hamcrest.Matchers.matchesPattern;
34 import static org.junit.Assert.assertEquals;
35 import static org.junit.Assert.assertNotEquals;
36 import static org.mockito.ArgumentMatchers.any;
37 import static org.mockito.ArgumentMatchers.anyMap;
38 import static org.mockito.ArgumentMatchers.anyString;
39 import static org.mockito.ArgumentMatchers.eq;
40 import static org.mockito.Mockito.mock;
41 import static org.mockito.Mockito.reset;
42 import static org.mockito.Mockito.when;
43
44 import com.google.common.collect.ImmutableList;
45 import io.joshworks.restclient.http.HttpResponse;
46 import java.nio.charset.StandardCharsets;
47 import java.util.Map;
48 import java.util.Optional;
49 import java.util.Set;
50 import java.util.UUID;
51 import java.util.function.Consumer;
52 import java.util.stream.Collectors;
53 import java.util.stream.Stream;
54 import javax.servlet.http.HttpServletRequest;
55 import javax.ws.rs.client.Client;
56 import javax.ws.rs.client.Invocation;
57 import javax.ws.rs.client.Invocation.Builder;
58 import javax.ws.rs.core.MultivaluedMap;
59 import org.apache.commons.lang3.reflect.FieldUtils;
60 import org.mockito.ArgumentCaptor;
61 import org.mockito.Captor;
62 import org.mockito.InjectMocks;
63 import org.mockito.Matchers;
64 import org.mockito.Mock;
65 import org.mockito.Mockito;
66 import org.mockito.MockitoAnnotations;
67 import org.onap.portalsdk.core.util.SystemProperties;
68 import org.onap.vid.aai.util.AAIRestInterface;
69 import org.onap.vid.aai.util.HttpsAuthClient;
70 import org.onap.vid.aai.util.ServletRequestHelper;
71 import org.onap.vid.aai.util.SystemPropertyHelper;
72 import org.onap.vid.client.SyncRestClient;
73 import org.onap.vid.controller.filter.PromiseRequestIdFilter;
74 import org.onap.vid.logging.Headers;
75 import org.onap.vid.mso.MsoProperties;
76 import org.onap.vid.mso.RestMsoImplementation;
77 import org.onap.vid.testUtils.TestUtils;
78 import org.onap.vid.utils.Logging;
79 import org.onap.vid.utils.SystemPropertiesWrapper;
80 import org.onap.vid.utils.Unchecked;
81 import org.springframework.http.HttpMethod;
82 import org.springframework.mock.web.MockHttpServletRequest;
83 import org.springframework.web.context.request.RequestContextHolder;
84 import org.springframework.web.context.request.ServletRequestAttributes;
85 import org.testng.annotations.BeforeClass;
86 import org.testng.annotations.BeforeMethod;
87 import org.testng.annotations.DataProvider;
88 import org.testng.annotations.Test;
89
90
91 public class OutgoingRequestHeadersTest {
92
93     private static final PromiseRequestIdFilter promiseRequestIdFilter = new PromiseRequestIdFilter();
94
95     @InjectMocks
96     private RestMsoImplementation restMsoImplementation;
97
98     private MsoRestClientNew msoRestClientNew;
99
100     @Mock
101     private SystemPropertyHelper systemPropertyHelper;
102
103     @Mock
104     private SystemPropertiesWrapper  systemPropertiesWrapper;
105
106     @Mock
107     private HttpsAuthClient httpsAuthClient;
108
109     @Mock
110     private ServletRequestHelper servletRequestHelper;
111
112     @Mock
113     private Logging loggingService;
114
115     @Mock
116     SyncRestClient syncRestClient;
117
118     @InjectMocks
119     private AAIRestInterface aaiRestInterface;
120
121     @Captor
122     private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor;
123
124     @BeforeClass
125     public void initMocks() {
126         MockitoAnnotations.initMocks(this);
127         String oneIncomingRequestId = UUID.randomUUID().toString();
128         when(servletRequestHelper.extractOrGenerateRequestId()).thenReturn(oneIncomingRequestId);
129         when(systemPropertiesWrapper.getProperty(MsoProperties.MSO_PASSWORD)).thenReturn("OBF:1vub1ua51uh81ugi1u9d1vuz");
130         when(systemPropertiesWrapper.getProperty(SystemProperties.APP_DISPLAY_NAME)).thenReturn("vid");
131         //the ctor of MsoRestClientNew require the above lines as preconditions
132         msoRestClientNew = new MsoRestClientNew(syncRestClient, "baseUrl",systemPropertiesWrapper);
133     }
134
135     @BeforeMethod
136     private void setup() {
137         putRequestInSpringContext();
138     }
139
140     public static void putRequestInSpringContext() {
141         RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(
142             (HttpServletRequest) promiseRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest())));
143     }
144
145     @DataProvider
146     public Object[][] msoMethods() {
147         return Stream.<ThrowingConsumer<RestMsoImplementation>>of(
148                 client -> client.GetForObject("/any path", Object.class),
149                 client -> client.restCall(HttpMethod.DELETE, Object.class, "some payload", "/any path", Optional.of("userId")),
150                 client -> client.PostForObject("some payload", "/any path", Object.class)
151         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
152     }
153
154     @Test
155     public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception {
156
157         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
158         String randomUserName = randomAlphabetic(10);
159
160         restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName));
161         assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID"));
162     }
163
164     @DataProvider
165     public Object[][] msoRestClientNewMethods() {
166         return Stream.<ThrowingConsumer<MsoRestClientNew>>of(
167             client -> client.createInstance(new Object(), "/any path")
168         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
169     }
170
171     @Test(dataProvider = "msoRestClientNewMethods")
172     public void msoRestClientNewHeadersTest(Consumer<MsoRestClientNew> f) throws Exception {
173         Map[] captor = setMocksForMsoRestClientNew();
174
175         f.accept(msoRestClientNew);
176         Map headers = captor[0];
177
178         String ecompRequestId = assertRequestHeaderIsUUID(headers, "X-ECOMP-RequestID");
179         String onapRequestID = assertRequestHeaderIsUUID(headers, "X-ONAP-RequestID");
180         assertEquals(ecompRequestId, onapRequestID);
181
182
183         String invocationId1 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
184         assertThat((String) headers.get("Authorization"), startsWith("Basic "));
185         assertThat(headers.get("X-ONAP-PartnerName"), is("VID.VID"));
186
187         //verify requestId is same in next call but invocationId is different
188
189         //given
190         captor = setMocksForMsoRestClientNew();
191
192         //when
193         f.accept(msoRestClientNew);
194         headers = captor[0];
195
196         //then
197         assertEquals(headers.get("X-ONAP-RequestID"), onapRequestID);
198         String invocationId2 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
199         assertNotEquals(invocationId1, invocationId2);
200
201     }
202
203     private Map[] setMocksForMsoRestClientNew() {
204         reset(syncRestClient);
205         HttpResponse<String> httpResponse = mock(HttpResponse.class);
206         String expectedResponse = "myResponse";
207         when(httpResponse.getStatus()).thenReturn(202);
208         when(httpResponse.getBody()).thenReturn(expectedResponse);
209         when(httpResponse.getRawBody()).thenReturn(toInputStream(expectedResponse, StandardCharsets.UTF_8));
210         final Map[] headersCapture = new Map[1];
211         when(syncRestClient.post(anyString(), anyMap(), any(), eq(String.class))).thenAnswer(
212             invocation -> {
213                 headersCapture[0] = (Map)invocation.getArguments()[1];
214                 return httpResponse;
215             });
216
217         return headersCapture;
218     }
219
220     @DataProvider
221     public Object[][] aaiMethods() {
222         return Stream.<ThrowingConsumer<AAIRestInterface>>of(
223
224                 client -> client.RestGet("from app id", "some transId", Unchecked.toURI("/any path"), false),
225                 client -> client.RestPost("from app id", "/any path", "some payload", false),
226                 client -> client.doRest("from app id", "some transId", Unchecked.toURI("/any path"), "somebody", HttpMethod.GET, false, true),
227                 client -> client.RestPut("from app id", "/any path", "some payload", false, false)
228
229         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
230     }
231
232     @Test(dataProvider = "aaiMethods")
233     public void aai(Consumer<AAIRestInterface> f) throws Exception {
234         //given
235         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface);
236         //when
237         f.accept(aaiRestInterface);
238         //then
239         HeadersVerifier headersVerifier = new HeadersVerifier().verifyFirstCall(mocks.getFakeBuilder());
240
241         //verify requestId is same in next call but invocationId is different
242         //given
243         final TestUtils.JavaxRsClientMocks mocks2 = setAndGetMocksInsideRestImpl(aaiRestInterface);
244         //when
245         f.accept(aaiRestInterface);
246         //then
247         headersVerifier.verifySecondCall(mocks2.getFakeBuilder());
248
249     }
250
251 //    @Test(dataProvider = "schedulerMethods")
252 //    public void scheduler(Consumer<AAIRestInterface> f) throws Exception {
253 //
254 //        This test os not feasible in the wat acheduler is implemented today,
255 //        as Scheduler's client is rewritten in every call.
256 //
257 //        :-(
258 //
259 //    }
260
261     private String verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
262         final String requestIdHeader = "x-ecomp-requestid";
263         return assertRequestHeaderIsUUID(fakeBuilder, requestIdHeader);
264     }
265
266     private String assertRequestHeaderIsUUID(Invocation.Builder fakeBuilder, String headerName) {
267         Object headerValue = captureHeaderKeyAndReturnItsValue(fakeBuilder, headerName);
268         return assertRequestHeaderIsUUID(headerName, headerValue);
269     }
270
271     private String assertRequestHeaderIsUUID(Map headers, String headerName) {
272         return assertRequestHeaderIsUUID(headerName, headers.get(headerName));
273     }
274
275     private String assertRequestHeaderIsUUID(String headerName, Object headerValue) {
276         final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
277         assertThat("header '" + headerName + "' should be a uuid", headerValue,
278                 allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex))));
279         return (String)headerValue;
280     }
281
282     private void verifyXOnapPartnerNameHeaderWasAdded(Invocation.Builder fakeBuilder) {
283         assertThat(
284             captureHeaderKeyAndReturnItsValue(fakeBuilder, Headers.PARTNER_NAME.getHeaderName()),
285             is("VID.VID")
286         );
287     }
288
289     private Object captureHeaderKeyAndReturnItsValue(Invocation.Builder fakeBuilder, String headerName) {
290         // Checks that the builder was called with either one of header("x-ecomp-requestid", uuid)
291         // or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid))
292
293         Object requestId;
294         // The 'verify()' will capture the request id. If no match -- AssertionError will
295         // catch for a second chance -- another 'verify()'.
296         try {
297             try {
298                 ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
299                 Mockito.verify(fakeBuilder)
300                     .header(
301                         Matchers.argThat(s -> equalsIgnoreCase(s, headerName)),
302                         argumentCaptor.capture()
303                     );
304                 requestId = argumentCaptor.getValue();
305
306             } catch (AssertionError e) {
307                 Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
308
309                 final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
310                 final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName);
311
312                 assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
313                 requestId = headersMap.getFirst(thisRequestIdHeader);
314             }
315         } catch (AssertionError e) {
316             throw new AssertionError("header not captured: " + headerName, e);
317         }
318         return requestId;
319     }
320
321     private String getFromSetCaseInsensitive(Set<String> set, String key) {
322         return set.stream()
323                 .filter(anotherString -> anotherString.equalsIgnoreCase(key))
324                 .findFirst()
325                 .orElse(key);
326     }
327
328     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException {
329         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
330         Client fakeClient = mocks.getFakeClient();
331
332         FieldUtils.writeStaticField(clazz, "client", fakeClient, true);
333
334         return mocks;
335     }
336
337     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException {
338         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
339         Client fakeClient = mocks.getFakeClient();
340
341         FieldUtils.writeField(instance, "client", fakeClient, true);
342
343         return mocks;
344     }
345
346     @FunctionalInterface
347     public interface ThrowingConsumer<T> extends Consumer<T> {
348         @Override
349         default void accept(T t) {
350             try {
351                 acceptThrows(t);
352             } catch (Exception e) {
353                 throw new RuntimeException(e);
354             }
355         }
356
357         void acceptThrows(T t) throws Exception;
358     }
359
360     private class HeadersVerifier {
361
362         private String firstRequestId;
363         private String firstInvocationId;
364
365
366         HeadersVerifier verifyFirstCall(Builder fakeBuilder) {
367             firstRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
368             assertEquals(firstRequestId, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID"));
369             firstInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
370             verifyXOnapPartnerNameHeaderWasAdded(fakeBuilder);
371             return this;
372         }
373
374         void verifySecondCall(Builder fakeBuilder) {
375             String secondRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
376             assertEquals(firstRequestId, secondRequestId);
377
378             Object secondInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
379             assertNotEquals(firstInvocationId, secondInvocationId);
380         }
381     }
382 }