Merge "Getter/setter tests inside the aai model"
[vid.git] / vid-app-common / src / test / java / org / onap / vid / mso / rest / OutgoingRequestIdTest.java
1 package org.onap.vid.mso.rest;
2
3 import com.google.common.collect.ImmutableList;
4 import org.apache.commons.lang3.reflect.FieldUtils;
5 import org.mockito.*;
6 import org.onap.vid.aai.util.AAIRestInterface;
7 import org.onap.vid.asdc.rest.RestfulAsdcClient;
8 import org.onap.vid.changeManagement.RequestDetailsWrapper;
9 import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter;
10 import org.onap.vid.mso.RestMsoImplementation;
11 import org.onap.vid.mso.RestObject;
12 import org.onap.vid.testUtils.TestUtils;
13 import org.springframework.mock.web.MockHttpServletRequest;
14 import org.springframework.web.context.request.RequestContextHolder;
15 import org.springframework.web.context.request.ServletRequestAttributes;
16 import org.testng.annotations.BeforeClass;
17 import org.testng.annotations.BeforeMethod;
18 import org.testng.annotations.DataProvider;
19 import org.testng.annotations.Test;
20
21 import javax.servlet.http.HttpServletRequest;
22 import javax.ws.rs.client.Client;
23 import javax.ws.rs.client.Invocation;
24 import javax.ws.rs.core.MultivaluedMap;
25 import java.util.Set;
26 import java.util.function.Consumer;
27 import java.util.stream.Collectors;
28 import java.util.stream.Stream;
29
30 import static java.util.UUID.randomUUID;
31 import static org.hamcrest.MatcherAssert.assertThat;
32 import static org.hamcrest.Matchers.*;
33 import static org.mockito.Mockito.mock;
34
35
36 public class OutgoingRequestIdTest {
37
38
39     @InjectMocks
40     private RestMsoImplementation restMsoImplementation;
41
42     @InjectMocks
43     private AAIRestInterface aaiRestInterface;
44
45     private RestfulAsdcClient restfulAsdcClient = new RestfulAsdcClient.Builder(mock(Client.class), null).build();
46
47     @Captor
48     private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor;
49
50     @BeforeClass
51     public void initMocks() {
52         MockitoAnnotations.initMocks(this);
53     }
54
55     @BeforeMethod
56     private void putRequestInSpringContext() {
57         RequestContextHolder.setRequestAttributes(new ServletRequestAttributes((HttpServletRequest) PromiseEcompRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest())));
58     }
59
60     @DataProvider
61     public Object[][] sdcMethods() {
62         return Stream.<ThrowingConsumer<RestfulAsdcClient>>of(
63                 client -> client.getService(randomUUID()),
64                 client -> client.getServiceToscaModel(randomUUID())
65         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
66     }
67
68     @Test(dataProvider = "sdcMethods")
69     public void sdc(Consumer<RestfulAsdcClient> f) throws Exception {
70         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restfulAsdcClient);
71
72         f.accept(restfulAsdcClient);
73
74         verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder());
75     }
76
77     @DataProvider
78     public Object[][] msoMethods() {
79         return Stream.<ThrowingConsumer<RestMsoImplementation>>of(
80
81                 client -> client.Get(new Object(), "whatever source id", "/any path", new RestObject<>()),
82                 client -> client.GetForObject("whatever source id", "/any path", Object.class),
83                 client -> client.Post(new Object(), "some payload", "whatever source id", "/any path", new RestObject<>()),
84                 client -> client.PostForObject("some payload", "whatever source id", "/any path", Object.class),
85                 client -> client.Put(Object.class, new RequestDetailsWrapper(), "whatever source id", "/any path", new RestObject<>())
86
87         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
88     }
89
90     @Test(dataProvider = "msoMethods")
91     public void mso(Consumer<RestMsoImplementation> f) throws Exception {
92         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation);
93
94         f.accept(restMsoImplementation);
95
96         verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder());
97     }
98
99     @DataProvider
100     public Object[][] aaiMethods() {
101         return Stream.<ThrowingConsumer<AAIRestInterface>>of(
102
103                 client -> client.RestGet("from app id", "some transId", "/any path", false),
104                 client -> client.Delete("whatever source id", "some transId", "/any path"),
105                 client -> client.RestPost("from app id", "/any path", "some payload", false),
106                 client -> client.RestPut("from app id", "/any path", "some payload", false)
107
108         ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{});
109     }
110
111     //@Test(dataProvider = "aaiMethods")
112     public void aai(Consumer<AAIRestInterface> f) throws Exception {
113         final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(aaiRestInterface);
114
115         f.accept(aaiRestInterface);
116
117         verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder());
118     }
119
120 //    @Test(dataProvider = "schedulerMethods")
121 //    public void scheduler(Consumer<AAIRestInterface> f) throws Exception {
122 //
123 //        This test os not feasible in the wat acheduler is implemented today,
124 //        as Scheduler's client is rewritten in every call.
125 //
126 //        :-(
127 //
128 //    }
129
130     private void verifyRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) {
131         final String requestIdHeader = "x-ecomp-requestid";
132         final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
133
134         // Checks that the builder was called with either one of header("x-ecomp-requestid", uuid)
135         // or the plural brother: headers(Map.of("x-ecomp-requestid", Set.of(uuid))
136
137         Object requestId;
138         // The 'verify()' will capture the request id. If no match -- AssertionError will
139         // catch for a second chance -- another 'verify()'.
140         try {
141             ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
142             Mockito.verify(fakeBuilder)
143                     .header(
144                             Matchers.argThat(equalToIgnoringCase(requestIdHeader)),
145                             argumentCaptor.capture()
146                     );
147             requestId = argumentCaptor.getValue();
148
149         } catch (AssertionError e) {
150             Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture());
151
152             final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue();
153             final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), requestIdHeader);
154
155             assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader));
156             requestId = headersMap.getFirst(thisRequestIdHeader);
157         }
158
159         assertThat("header '" + requestIdHeader + "' should be a uuid", requestId,
160                 allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex))));
161     }
162
163     private String getFromSetCaseInsensitive(Set<String> set, String key) {
164         return set.stream()
165                 .filter(anotherString -> anotherString.equalsIgnoreCase(key))
166                 .findFirst()
167                 .orElse(key);
168     }
169
170     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Class<?> clazz) throws IllegalAccessException {
171         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
172         Client fakeClient = mocks.getFakeClient();
173
174         FieldUtils.writeStaticField(clazz, "client", fakeClient, true);
175
176         return mocks;
177     }
178
179     private TestUtils.JavaxRsClientMocks setAndGetMocksInsideRestImpl(Object instance) throws IllegalAccessException {
180         TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks();
181         Client fakeClient = mocks.getFakeClient();
182
183         FieldUtils.writeField(instance, "client", fakeClient, true);
184
185         return mocks;
186     }
187
188     @FunctionalInterface
189     public interface ThrowingConsumer<T> extends Consumer<T> {
190         @Override
191         default void accept(T t) {
192             try {
193                 acceptThrows(t);
194             } catch (Exception e) {
195                 throw new RuntimeException(e);
196             }
197         }
198
199         void acceptThrows(T t) throws Exception;
200     }
201
202 }