ac05ea706508a755bbbb1a50acacdc0447bc1fb5
[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.lang3.StringUtils.equalsIgnoreCase;
24 import static org.hamcrest.MatcherAssert.assertThat;
25 import static org.hamcrest.Matchers.allOf;
26 import static org.hamcrest.Matchers.hasItem;
27 import static org.hamcrest.Matchers.hasToString;
28 import static org.hamcrest.Matchers.instanceOf;
29 import static org.hamcrest.Matchers.matchesPattern;
30 import static org.mockito.Mockito.when;
31
32 import com.google.common.collect.ImmutableList;
33 import java.util.Set;
34 import java.util.UUID;
35 import java.util.function.Consumer;
36 import java.util.stream.Collectors;
37 import java.util.stream.Stream;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.ws.rs.client.Client;
40 import javax.ws.rs.client.Invocation;
41 import javax.ws.rs.core.MultivaluedMap;
42 import org.apache.commons.lang3.reflect.FieldUtils;
43 import org.mockito.ArgumentCaptor;
44 import org.mockito.Captor;
45 import org.mockito.InjectMocks;
46 import org.mockito.Matchers;
47 import org.mockito.Mock;
48 import org.mockito.Mockito;
49 import org.mockito.MockitoAnnotations;
50 import org.onap.vid.aai.util.AAIRestInterface;
51 import org.onap.vid.aai.util.ServletRequestHelper;
52 import org.onap.vid.aai.util.SystemPropertyHelper;
53 import org.onap.vid.controller.filter.PromiseRequestIdFilter;
54 import org.onap.vid.testUtils.TestUtils;
55 import org.onap.vid.utils.Logging;
56 import org.onap.vid.utils.Unchecked;
57 import org.springframework.mock.web.MockHttpServletRequest;
58 import org.springframework.web.context.request.RequestContextHolder;
59 import org.springframework.web.context.request.ServletRequestAttributes;
60 import org.testng.annotations.BeforeClass;
61 import org.testng.annotations.BeforeMethod;
62 import org.testng.annotations.DataProvider;
63 import org.testng.annotations.Test;
64
65
66 public class OutgoingRequestHeadersTest {
67
68     private static final PromiseRequestIdFilter promiseRequestIdFilter = new PromiseRequestIdFilter();
69
70 //    @InjectMocks
71 //    private RestMsoImplementation restMsoImplementation;
72
73     @Mock
74     private SystemPropertyHelper systemPropertyHelper;
75
76     @Mock
77     private ServletRequestHelper servletRequestHelper;
78
79     @Mock
80     private Logging loggingService;
81
82     @InjectMocks
83     private AAIRestInterface aaiRestInterface;
84
85     @Captor
86     private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor;
87
88     @BeforeClass
89     public void initMocks() {
90         MockitoAnnotations.initMocks(this);
91         when(servletRequestHelper.extractOrGenerateRequestId()).thenAnswer(invocation -> UUID.randomUUID().toString());
92     }
93
94     @BeforeMethod
95     private void setup() {
96         putRequestInSpringContext();
97     }
98
99     public static void putRequestInSpringContext() {
100         RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(
101             (HttpServletRequest) promiseRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest())));
102     }
103
104 //    @DataProvider
105 //    public Object[][] msoMethods() {
106 //        return Stream.<ThrowingConsumer<RestMsoImplementation>>of(
107 //
108 //                client -> client.Get(new Object(), "/any path", new RestObject<>(), false),
109 //                client -> client.GetForObject("/any path", Object.class),
110 //                client -> client.Post("", "some payload", "/any path", new RestObject<>()),
111 //                client -> client.PostForObject("some payload", "/any path", Object.class),
112 //                client -> client.Put(Object.class, new RequestDetailsWrapper(), "/any path", new RestObject<>())
113 //
114 //        ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
115 //    }
116 //
117 //    @Test(dataProvider = "msoMethods")
118 //    public void mso(Consumer<RestMsoImplementation> f) throws Exception {
119 //        final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
120 //
121 //        f.accept(restMsoImplementation);
122 //
123 //        Invocation.Builder fakeBuilder = mocks.getFakeBuilder();
124 //        Object requestIdValue = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder);
125 //        assertEquals(requestIdValue, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID"));
126 //
127 //        assertThat((String) captureHeaderKeyAndReturnItsValue(fakeBuilder, "Authorization"), startsWith("Basic "));
128 //        assertThat(captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-PartnerName"), equalTo("VID"));
129 //    }
130 //
131 //    @Test
132 //    public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception {
133 //
134 //        final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
135 //        String randomUserName = randomAlphabetic(10);
136 //
137 //        restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName));
138 //        assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID"));
139 //    }
140
141     @DataProvider
142     public Object[][] aaiMethods() {
143         return Stream.<ThrowingConsumer<AAIRestInterface>>of(
144
145                 client -> client.RestGet("from app id", "some transId", Unchecked.toURI("/any path"), false),
146                 client -> client.Delete("whatever source id", "some transId", "/any path"),
147                 client -> client.RestPost("from app id", "/any path", "some payload", false),
148                 client -> client.RestPut("from app id", "/any path", "some payload", false, false)
149
150         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
151     }
152
153     @Test(dataProvider = "aaiMethods")
154     public void aai(Consumer<AAIRestInterface> f) throws Exception {
155         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface);
156
157         f.accept(aaiRestInterface);
158
159         verifyXEcompRequestIdHeaderWasAdded(mocks.getFakeBuilder());
160     }
161
162 //    @Test(dataProvider = "schedulerMethods")
163 //    public void scheduler(Consumer<AAIRestInterface> f) throws Exception {
164 //
165 //        This test os not feasible in the wat acheduler is implemented today,
166 //        as Scheduler's client is rewritten in every call.
167 //
168 //        :-(
169 //
170 //    }
171
172     private Object verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
173         final String requestIdHeader = "x-ecomp-requestid";
174         final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
175         Object requestId = captureHeaderKeyAndReturnItsValue(fakeBuilder, requestIdHeader);
176
177         assertThat("header '" + requestIdHeader + "' should be a uuid", requestId,
178                 allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex))));
179         return requestId;
180     }
181
182     private Object captureHeaderKeyAndReturnItsValue(Invocation.Builder fakeBuilder, String headerName) {
183         // Checks that the builder was called with either one of header("x-ecomp-requestid", uuid)
184         // or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid))
185
186         Object requestId;
187         // The 'verify()' will capture the request id. If no match -- AssertionError will
188         // catch for a second chance -- another 'verify()'.
189         try {
190             ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
191             Mockito.verify(fakeBuilder)
192                     .header(
193                             Matchers.argThat(s -> equalsIgnoreCase(s, headerName)),
194                             argumentCaptor.capture()
195                     );
196             requestId = argumentCaptor.getValue();
197
198         } catch (AssertionError e) {
199             Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
200
201             final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
202             final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName);
203
204             assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
205             requestId = headersMap.getFirst(thisRequestIdHeader);
206         }
207         return requestId;
208     }
209
210     private String getFromSetCaseInsensitive(Set<String> set, String key) {
211         return set.stream()
212                 .filter(anotherString -> anotherString.equalsIgnoreCase(key))
213                 .findFirst()
214                 .orElse(key);
215     }
216
217     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException {
218         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
219         Client fakeClient = mocks.getFakeClient();
220
221         FieldUtils.writeStaticField(clazz, "client", fakeClient, true);
222
223         return mocks;
224     }
225
226     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException {
227         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
228         Client fakeClient = mocks.getFakeClient();
229
230         FieldUtils.writeField(instance, "client", fakeClient, true);
231
232         return mocks;
233     }
234
235     @FunctionalInterface
236     public interface ThrowingConsumer<T> extends Consumer<T> {
237         @Override
238         default void accept(T t) {
239             try {
240                 acceptThrows(t);
241             } catch (Exception e) {
242                 throw new RuntimeException(e);
243             }
244         }
245
246         void acceptThrows(T t) throws Exception;
247     }
248
249 }