2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.mso.rest;
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;
44 import com.google.common.collect.ImmutableList;
45 import io.joshworks.restclient.http.HttpResponse;
46 import java.nio.charset.StandardCharsets;
48 import java.util.Optional;
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;
91 public class OutgoingRequestHeadersTest {
93 private static final PromiseRequestIdFilter promiseRequestIdFilter = new PromiseRequestIdFilter();
96 private RestMsoImplementation restMsoImplementation;
98 private MsoRestClientNew msoRestClientNew;
101 private SystemPropertyHelper systemPropertyHelper;
104 private SystemPropertiesWrapper systemPropertiesWrapper;
107 private HttpsAuthClient httpsAuthClient;
110 private ServletRequestHelper servletRequestHelper;
113 private Logging loggingService;
116 SyncRestClient syncRestClient;
119 private AAIRestInterface aaiRestInterface;
122 private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor;
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);
136 private void setup() {
137 putRequestInSpringContext();
140 public static void putRequestInSpringContext() {
141 RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(
142 (HttpServletRequest) promiseRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest())));
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[][]{});
155 public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception {
157 final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
158 String randomUserName = randomAlphabetic(10);
160 restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName));
161 assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID"));
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[][]{});
171 @Test(dataProvider = "msoRestClientNewMethods")
172 public void msoRestClientNewHeadersTest(Consumer<MsoRestClientNew> f) throws Exception {
173 Map[] captor = setMocksForMsoRestClientNew();
175 f.accept(msoRestClientNew);
176 Map headers = captor[0];
178 String ecompRequestId = assertRequestHeaderIsUUID(headers, "X-ECOMP-RequestID");
179 String onapRequestID = assertRequestHeaderIsUUID(headers, "X-ONAP-RequestID");
180 assertEquals(ecompRequestId, onapRequestID);
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"));
187 //verify requestId is same in next call but invocationId is different
190 captor = setMocksForMsoRestClientNew();
193 f.accept(msoRestClientNew);
197 assertEquals(headers.get("X-ONAP-RequestID"), onapRequestID);
198 String invocationId2 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
199 assertNotEquals(invocationId1, invocationId2);
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(
213 headersCapture[0] = (Map)invocation.getArguments()[1];
217 return headersCapture;
221 public Object[][] aaiMethods() {
222 return Stream.<ThrowingConsumer<AAIRestInterface>>of(
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)
229 ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
232 @Test(dataProvider = "aaiMethods")
233 public void aai(Consumer<AAIRestInterface> f) throws Exception {
235 final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface);
237 f.accept(aaiRestInterface);
239 HeadersVerifier headersVerifier = new HeadersVerifier().verifyFirstCall(mocks.getFakeBuilder());
241 //verify requestId is same in next call but invocationId is different
243 final TestUtils.JavaxRsClientMocks mocks2 = setAndGetMocksInsideRestImpl(aaiRestInterface);
245 f.accept(aaiRestInterface);
247 headersVerifier.verifySecondCall(mocks2.getFakeBuilder());
251 // @Test(dataProvider = "schedulerMethods")
252 // public void scheduler(Consumer<AAIRestInterface> f) throws Exception {
254 // This test os not feasible in the wat acheduler is implemented today,
255 // as Scheduler's client is rewritten in every call.
261 private String verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
262 final String requestIdHeader = "x-ecomp-requestid";
263 return assertRequestHeaderIsUUID(fakeBuilder, requestIdHeader);
266 private String assertRequestHeaderIsUUID(Invocation.Builder fakeBuilder, String headerName) {
267 Object headerValue = captureHeaderKeyAndReturnItsValue(fakeBuilder, headerName);
268 return assertRequestHeaderIsUUID(headerName, headerValue);
271 private String assertRequestHeaderIsUUID(Map headers, String headerName) {
272 return assertRequestHeaderIsUUID(headerName, headers.get(headerName));
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;
282 private void verifyXOnapPartnerNameHeaderWasAdded(Invocation.Builder fakeBuilder) {
284 captureHeaderKeyAndReturnItsValue(fakeBuilder, Headers.PARTNER_NAME.getHeaderName()),
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))
294 // The 'verify()' will capture the request id. If no match -- AssertionError will
295 // catch for a second chance -- another 'verify()'.
298 ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
299 Mockito.verify(fakeBuilder)
301 Matchers.argThat(s -> equalsIgnoreCase(s, headerName)),
302 argumentCaptor.capture()
304 requestId = argumentCaptor.getValue();
306 } catch (AssertionError e) {
307 Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
309 final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
310 final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName);
312 assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
313 requestId = headersMap.getFirst(thisRequestIdHeader);
315 } catch (AssertionError e) {
316 throw new AssertionError("header not captured: " + headerName, e);
321 private String getFromSetCaseInsensitive(Set<String> set, String key) {
323 .filter(anotherString -> anotherString.equalsIgnoreCase(key))
328 private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException {
329 TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
330 Client fakeClient = mocks.getFakeClient();
332 FieldUtils.writeStaticField(clazz, "client", fakeClient, true);
337 private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException {
338 TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
339 Client fakeClient = mocks.getFakeClient();
341 FieldUtils.writeField(instance, "client", fakeClient, true);
347 public interface ThrowingConsumer<T> extends Consumer<T> {
349 default void accept(T t) {
352 } catch (Exception e) {
353 throw new RuntimeException(e);
357 void acceptThrows(T t) throws Exception;
360 private class HeadersVerifier {
362 private String firstRequestId;
363 private String firstInvocationId;
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);
374 void verifySecondCall(Builder fakeBuilder) {
375 String secondRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
376 assertEquals(firstRequestId, secondRequestId);
378 Object secondInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
379 assertNotEquals(firstInvocationId, secondInvocationId);