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(dataProvider = "msoMethods")
155     public void mso(Consumer<RestMsoImplementation> f) throws Exception {
156         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
157
158         f.accept(restMsoImplementation);
159         HeadersVerifier headersVerifier = new HeadersVerifier().verifyFirstCall(mocks.getFakeBuilder());
160
161         assertThat((String) captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "Authorization"), startsWith("Basic "));
162
163         //verify requestId is same in next call but invocationId is different
164
165         //given
166         final TestUtils.JavaxRsClientMocks mocks2 = setAndGetMocksInsideRestImpl(restMsoImplementation);
167
168         //when
169         f.accept(restMsoImplementation);
170         //then
171         headersVerifier.verifySecondCall(mocks2.getFakeBuilder());
172     }
173
174
175
176     @Test
177     public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception {
178
179         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
180         String randomUserName = randomAlphabetic(10);
181
182         restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName));
183         assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID"));
184     }
185
186     @DataProvider
187     public Object[][] msoRestClientNewMethods() {
188         return Stream.<ThrowingConsumer<MsoRestClientNew>>of(
189             client -> client.createInstance(new Object(), "/any path")
190         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
191     }
192
193     @Test(dataProvider = "msoRestClientNewMethods")
194     public void msoRestClientNewHeadersTest(Consumer<MsoRestClientNew> f) throws Exception {
195         Map[] captor = setMocksForMsoRestClientNew();
196
197         f.accept(msoRestClientNew);
198         Map headers = captor[0];
199
200         String ecompRequestId = assertRequestHeaderIsUUID(headers, "X-ECOMP-RequestID");
201         String onapRequestID = assertRequestHeaderIsUUID(headers, "X-ONAP-RequestID");
202         assertEquals(ecompRequestId, onapRequestID);
203
204
205         String invocationId1 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
206         assertThat((String) headers.get("Authorization"), startsWith("Basic "));
207         assertThat(headers.get("X-ONAP-PartnerName"), is("VID.VID"));
208
209         //verify requestId is same in next call but invocationId is different
210
211         //given
212         captor = setMocksForMsoRestClientNew();
213
214         //when
215         f.accept(msoRestClientNew);
216         headers = captor[0];
217
218         //then
219         assertEquals(headers.get("X-ONAP-RequestID"), onapRequestID);
220         String invocationId2 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
221         assertNotEquals(invocationId1, invocationId2);
222
223     }
224
225     private Map[] setMocksForMsoRestClientNew() {
226         reset(syncRestClient);
227         HttpResponse<String> httpResponse = mock(HttpResponse.class);
228         String expectedResponse = "myResponse";
229         when(httpResponse.getStatus()).thenReturn(202);
230         when(httpResponse.getBody()).thenReturn(expectedResponse);
231         when(httpResponse.getRawBody()).thenReturn(toInputStream(expectedResponse, StandardCharsets.UTF_8));
232         final Map[] headersCapture = new Map[1];
233         when(syncRestClient.post(anyString(), anyMap(), any(), eq(String.class))).thenAnswer(
234             invocation -> {
235                 headersCapture[0] = (Map)invocation.getArguments()[1];
236                 return httpResponse;
237             });
238
239         return headersCapture;
240     }
241
242     @DataProvider
243     public Object[][] aaiMethods() {
244         return Stream.<ThrowingConsumer<AAIRestInterface>>of(
245
246                 client -> client.RestGet("from app id", "some transId", Unchecked.toURI("/any path"), false),
247                 client -> client.RestPost("from app id", "/any path", "some payload", false),
248                 client -> client.doRest("from app id", "some transId", Unchecked.toURI("/any path"), "somebody", HttpMethod.GET, false, true),
249                 client -> client.RestPut("from app id", "/any path", "some payload", false, false)
250
251         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
252     }
253
254     @Test(dataProvider = "aaiMethods")
255     public void aai(Consumer<AAIRestInterface> f) throws Exception {
256         //given
257         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface);
258         //when
259         f.accept(aaiRestInterface);
260         //then
261         HeadersVerifier headersVerifier = new HeadersVerifier().verifyFirstCall(mocks.getFakeBuilder());
262
263         //verify requestId is same in next call but invocationId is different
264         //given
265         final TestUtils.JavaxRsClientMocks mocks2 = setAndGetMocksInsideRestImpl(aaiRestInterface);
266         //when
267         f.accept(aaiRestInterface);
268         //then
269         headersVerifier.verifySecondCall(mocks2.getFakeBuilder());
270
271     }
272
273 //    @Test(dataProvider = "schedulerMethods")
274 //    public void scheduler(Consumer<AAIRestInterface> f) throws Exception {
275 //
276 //        This test os not feasible in the wat acheduler is implemented today,
277 //        as Scheduler's client is rewritten in every call.
278 //
279 //        :-(
280 //
281 //    }
282
283     private String verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
284         final String requestIdHeader = "x-ecomp-requestid";
285         return assertRequestHeaderIsUUID(fakeBuilder, requestIdHeader);
286     }
287
288     private String assertRequestHeaderIsUUID(Invocation.Builder fakeBuilder, String headerName) {
289         Object headerValue = captureHeaderKeyAndReturnItsValue(fakeBuilder, headerName);
290         return assertRequestHeaderIsUUID(headerName, headerValue);
291     }
292
293     private String assertRequestHeaderIsUUID(Map headers, String headerName) {
294         return assertRequestHeaderIsUUID(headerName, headers.get(headerName));
295     }
296
297     private String assertRequestHeaderIsUUID(String headerName, Object headerValue) {
298         final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
299         assertThat("header '" + headerName + "' should be a uuid", headerValue,
300                 allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex))));
301         return (String)headerValue;
302     }
303
304     private void verifyXOnapPartnerNameHeaderWasAdded(Invocation.Builder fakeBuilder) {
305         assertThat(
306             captureHeaderKeyAndReturnItsValue(fakeBuilder, Headers.PARTNER_NAME.getHeaderName()),
307             is("VID.VID")
308         );
309     }
310
311     private Object captureHeaderKeyAndReturnItsValue(Invocation.Builder fakeBuilder, String headerName) {
312         // Checks that the builder was called with either one of header("x-ecomp-requestid", uuid)
313         // or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid))
314
315         Object requestId;
316         // The 'verify()' will capture the request id. If no match -- AssertionError will
317         // catch for a second chance -- another 'verify()'.
318         try {
319             try {
320                 ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
321                 Mockito.verify(fakeBuilder)
322                     .header(
323                         Matchers.argThat(s -> equalsIgnoreCase(s, headerName)),
324                         argumentCaptor.capture()
325                     );
326                 requestId = argumentCaptor.getValue();
327
328             } catch (AssertionError e) {
329                 Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
330
331                 final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
332                 final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName);
333
334                 assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
335                 requestId = headersMap.getFirst(thisRequestIdHeader);
336             }
337         } catch (AssertionError e) {
338             throw new AssertionError("header not captured: " + headerName, e);
339         }
340         return requestId;
341     }
342
343     private String getFromSetCaseInsensitive(Set<String> set, String key) {
344         return set.stream()
345                 .filter(anotherString -> anotherString.equalsIgnoreCase(key))
346                 .findFirst()
347                 .orElse(key);
348     }
349
350     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException {
351         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
352         Client fakeClient = mocks.getFakeClient();
353
354         FieldUtils.writeStaticField(clazz, "client", fakeClient, true);
355
356         return mocks;
357     }
358
359     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException {
360         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
361         Client fakeClient = mocks.getFakeClient();
362
363         FieldUtils.writeField(instance, "client", fakeClient, true);
364
365         return mocks;
366     }
367
368     @FunctionalInterface
369     public interface ThrowingConsumer<T> extends Consumer<T> {
370         @Override
371         default void accept(T t) {
372             try {
373                 acceptThrows(t);
374             } catch (Exception e) {
375                 throw new RuntimeException(e);
376             }
377         }
378
379         void acceptThrows(T t) throws Exception;
380     }
381
382     private class HeadersVerifier {
383
384         private String firstRequestId;
385         private String firstInvocationId;
386
387
388         HeadersVerifier verifyFirstCall(Builder fakeBuilder) {
389             firstRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
390             assertEquals(firstRequestId, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID"));
391             firstInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
392             verifyXOnapPartnerNameHeaderWasAdded(fakeBuilder);
393             return this;
394         }
395
396         void verifySecondCall(Builder fakeBuilder) {
397             String secondRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
398             assertEquals(firstRequestId, secondRequestId);
399
400             Object secondInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
401             assertNotEquals(firstInvocationId, secondInvocationId);
402         }
403     }
404 }