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[][]{});
154 @Test(dataProvider = "msoMethods")
155 public void mso(Consumer<RestMsoImplementation> f) throws Exception {
156 final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
158 f.accept(restMsoImplementation);
159 HeadersVerifier headersVerifier = new HeadersVerifier().verifyFirstCall(mocks.getFakeBuilder());
161 assertThat((String) captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "Authorization"), startsWith("Basic "));
163 //verify requestId is same in next call but invocationId is different
166 final TestUtils.JavaxRsClientMocks mocks2 = setAndGetMocksInsideRestImpl(restMsoImplementation);
169 f.accept(restMsoImplementation);
171 headersVerifier.verifySecondCall(mocks2.getFakeBuilder());
177 public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception {
179 final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
180 String randomUserName = randomAlphabetic(10);
182 restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName));
183 assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID"));
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[][]{});
193 @Test(dataProvider = "msoRestClientNewMethods")
194 public void msoRestClientNewHeadersTest(Consumer<MsoRestClientNew> f) throws Exception {
195 Map[] captor = setMocksForMsoRestClientNew();
197 f.accept(msoRestClientNew);
198 Map headers = captor[0];
200 String ecompRequestId = assertRequestHeaderIsUUID(headers, "X-ECOMP-RequestID");
201 String onapRequestID = assertRequestHeaderIsUUID(headers, "X-ONAP-RequestID");
202 assertEquals(ecompRequestId, onapRequestID);
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"));
209 //verify requestId is same in next call but invocationId is different
212 captor = setMocksForMsoRestClientNew();
215 f.accept(msoRestClientNew);
219 assertEquals(headers.get("X-ONAP-RequestID"), onapRequestID);
220 String invocationId2 = assertRequestHeaderIsUUID(headers, "X-InvocationID");
221 assertNotEquals(invocationId1, invocationId2);
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(
235 headersCapture[0] = (Map)invocation.getArguments()[1];
239 return headersCapture;
243 public Object[][] aaiMethods() {
244 return Stream.<ThrowingConsumer<AAIRestInterface>>of(
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)
251 ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
254 @Test(dataProvider = "aaiMethods")
255 public void aai(Consumer<AAIRestInterface> f) throws Exception {
257 final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface);
259 f.accept(aaiRestInterface);
261 HeadersVerifier headersVerifier = new HeadersVerifier().verifyFirstCall(mocks.getFakeBuilder());
263 //verify requestId is same in next call but invocationId is different
265 final TestUtils.JavaxRsClientMocks mocks2 = setAndGetMocksInsideRestImpl(aaiRestInterface);
267 f.accept(aaiRestInterface);
269 headersVerifier.verifySecondCall(mocks2.getFakeBuilder());
273 // @Test(dataProvider = "schedulerMethods")
274 // public void scheduler(Consumer<AAIRestInterface> f) throws Exception {
276 // This test os not feasible in the wat acheduler is implemented today,
277 // as Scheduler's client is rewritten in every call.
283 private String verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
284 final String requestIdHeader = "x-ecomp-requestid";
285 return assertRequestHeaderIsUUID(fakeBuilder, requestIdHeader);
288 private String assertRequestHeaderIsUUID(Invocation.Builder fakeBuilder, String headerName) {
289 Object headerValue = captureHeaderKeyAndReturnItsValue(fakeBuilder, headerName);
290 return assertRequestHeaderIsUUID(headerName, headerValue);
293 private String assertRequestHeaderIsUUID(Map headers, String headerName) {
294 return assertRequestHeaderIsUUID(headerName, headers.get(headerName));
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;
304 private void verifyXOnapPartnerNameHeaderWasAdded(Invocation.Builder fakeBuilder) {
306 captureHeaderKeyAndReturnItsValue(fakeBuilder, Headers.PARTNER_NAME.getHeaderName()),
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))
316 // The 'verify()' will capture the request id. If no match -- AssertionError will
317 // catch for a second chance -- another 'verify()'.
320 ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
321 Mockito.verify(fakeBuilder)
323 Matchers.argThat(s -> equalsIgnoreCase(s, headerName)),
324 argumentCaptor.capture()
326 requestId = argumentCaptor.getValue();
328 } catch (AssertionError e) {
329 Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
331 final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
332 final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName);
334 assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
335 requestId = headersMap.getFirst(thisRequestIdHeader);
337 } catch (AssertionError e) {
338 throw new AssertionError("header not captured: " + headerName, e);
343 private String getFromSetCaseInsensitive(Set<String> set, String key) {
345 .filter(anotherString -> anotherString.equalsIgnoreCase(key))
350 private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException {
351 TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
352 Client fakeClient = mocks.getFakeClient();
354 FieldUtils.writeStaticField(clazz, "client", fakeClient, true);
359 private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException {
360 TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
361 Client fakeClient = mocks.getFakeClient();
363 FieldUtils.writeField(instance, "client", fakeClient, true);
369 public interface ThrowingConsumer<T> extends Consumer<T> {
371 default void accept(T t) {
374 } catch (Exception e) {
375 throw new RuntimeException(e);
379 void acceptThrows(T t) throws Exception;
382 private class HeadersVerifier {
384 private String firstRequestId;
385 private String firstInvocationId;
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);
396 void verifySecondCall(Builder fakeBuilder) {
397 String secondRequestId = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
398 assertEquals(firstRequestId, secondRequestId);
400 Object secondInvocationId = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID");
401 assertNotEquals(firstInvocationId, secondInvocationId);