logging of HttpResponse use raw body
[vid.git] / vid-app-common / src / test / java / org / onap / vid / testUtils / TestUtils.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.testUtils;
22
23 import static com.fasterxml.jackson.module.kotlin.ExtensionsKt.jacksonObjectMapper;
24 import static java.util.function.Function.identity;
25 import static java.util.stream.Collectors.toList;
26 import static java.util.stream.Collectors.toMap;
27 import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors;
28 import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
29 import static org.apache.commons.text.CharacterPredicates.DIGITS;
30 import static org.apache.commons.text.CharacterPredicates.LETTERS;
31 import static org.apache.http.HttpVersion.HTTP_1_1;
32 import static org.mockito.ArgumentMatchers.any;
33 import static org.mockito.Mockito.RETURNS_DEFAULTS;
34 import static org.mockito.Mockito.mock;
35 import static org.mockito.Mockito.when;
36 import static org.mockito.Mockito.withSettings;
37 import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
38 import static org.onap.vid.utils.KotlinUtilsKt.JOSHWORKS_JACKSON_OBJECT_MAPPER;
39 import static org.testng.Assert.fail;
40
41 import com.fasterxml.jackson.databind.DeserializationFeature;
42 import com.fasterxml.jackson.databind.ObjectMapper;
43 import com.google.code.beanmatchers.BeanMatchers;
44 import com.google.common.collect.ImmutableList;
45 import io.joshworks.restclient.http.HttpResponse;
46 import java.beans.PropertyDescriptor;
47 import java.io.ByteArrayInputStream;
48 import java.io.IOException;
49 import java.io.InputStream;
50 import java.io.Serializable;
51 import java.lang.reflect.Field;
52 import java.net.URI;
53 import java.nio.charset.StandardCharsets;
54 import java.util.Arrays;
55 import java.util.Iterator;
56 import java.util.List;
57 import java.util.function.Predicate;
58 import javax.ws.rs.client.Client;
59 import javax.ws.rs.client.Invocation;
60 import javax.ws.rs.client.WebTarget;
61 import javax.ws.rs.core.GenericType;
62 import javax.ws.rs.core.MediaType;
63 import javax.ws.rs.core.Response;
64 import org.apache.commons.beanutils.BeanUtils;
65 import org.apache.commons.io.IOUtils;
66 import org.apache.commons.lang3.exception.ExceptionUtils;
67 import org.apache.commons.lang3.reflect.FieldUtils;
68 import org.apache.commons.lang3.reflect.MethodUtils;
69 import org.apache.commons.text.RandomStringGenerator;
70 import org.apache.http.HttpResponseFactory;
71 import org.apache.http.entity.InputStreamEntity;
72 import org.apache.http.entity.StringEntity;
73 import org.apache.http.impl.DefaultHttpResponseFactory;
74 import org.apache.http.message.BasicStatusLine;
75 import org.apache.log4j.LogManager;
76 import org.apache.log4j.Logger;
77 import org.json.JSONArray;
78 import org.json.JSONObject;
79 import org.junit.Assert;
80 import org.mockito.InjectMocks;
81 import org.mockito.Mock;
82 import org.mockito.MockSettings;
83 import org.mockito.Mockito;
84 import org.mockito.MockitoAnnotations;
85 import org.mockito.invocation.InvocationOnMock;
86 import org.mockito.stubbing.Answer;
87 import org.mockito.stubbing.OngoingStubbing;
88 import org.onap.portalsdk.core.util.SystemProperties;
89 import org.onap.vid.asdc.AsdcCatalogException;
90 import org.onap.vid.asdc.beans.Service;
91 import org.onap.vid.mso.model.CloudConfiguration;
92 import org.springframework.core.env.Environment;
93 import org.testng.annotations.DataProvider;
94
95 /**
96  * Created by Oren on 6/7/17.
97  */
98 public class TestUtils {
99
100     private static final Logger logger = LogManager.getLogger(TestUtils.class);
101
102     /**
103      * The method compares between two jsons. the function assert that the actual object does not reduce or change the functionallity/parsing of the expected json.
104      * This means that if the expected JSON has a key which is null or the JSON doesn't have a key which contained in the expected JSON the assert will succeed and the will pass.
105      * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
106      * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
107      *
108      * @param expected JSON
109      * @param actual JSON
110      */
111     public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
112         if (expected == null || expected == JSONObject.NULL) {return;}
113
114         JSONObject expectedJSON = new JSONObject(expected);
115         JSONObject actualJSON = new JSONObject(actual);
116         Iterator<?> keys = expectedJSON.keys();
117
118         while( keys.hasNext() ) {
119             String key = (String)keys.next();
120             Object expectedValue = expectedJSON.get(key);
121             if (expectedValue == JSONObject.NULL){
122                 continue;
123             }
124
125             Object actualValue = actualJSON.get(key);
126
127             if (expectedValue instanceof JSONObject) {
128                 String expectedVal = expectedValue.toString();
129                 String actualVal = actualValue.toString();
130                 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
131             }
132             else if (expectedValue instanceof JSONArray) {
133                 if (actualValue instanceof JSONArray) {
134                     JSONArray expectedJSONArray = (JSONArray)expectedValue;
135                     JSONArray actualJSONArray = (JSONArray)actualValue;
136                     for (int i = 0; i < expectedJSONArray.length(); i++) {
137                         String expectedItem = expectedJSONArray.get(i).toString();
138                         String actualItem = actualJSONArray.get(i).toString();
139                         if (expectedValue instanceof JSONObject)
140                             assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
141                     }
142                 }
143                 else {
144                     fail("expected: " + expectedValue + " got:" + actualValue);
145                 }
146             }
147             else {
148                 Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
149             }
150         }
151     }
152
153     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
154         return readJsonResourceFileAsObject(pathInResource, valueType, false);
155     }
156
157     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType,
158         boolean failOnUnknownProperties)
159         throws IOException {
160         ObjectMapper objectMapper = jacksonObjectMapper()
161             .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties);
162         return objectMapper.readValue(
163             TestUtils.class.getResource(pathInResource),
164             valueType);
165     }
166
167     public static String readFileAsString(String pathInResource) {
168         try {
169             return IOUtils.toString(TestUtils.class.getResource(pathInResource), "UTF-8");
170         } catch (IOException e) {
171             throw new RuntimeException(e);
172         }
173     }
174
175     public static String[] allPropertiesOf(Class<?> aClass) {
176         return Arrays.stream(getPropertyDescriptors(aClass))
177             .map(PropertyDescriptor::getDisplayName)
178             .toArray(String[]::new);
179     }
180
181     private static <T> List<String> allStringPropertiesOf(T object) {
182         return Arrays.stream(getPropertyDescriptors(object.getClass()))
183             .filter(descriptor -> descriptor.getPropertyType().isAssignableFrom(String.class))
184             .map(PropertyDescriptor::getDisplayName)
185             .collect(toList());
186     }
187
188     private static List<Field> allMockitoFieldsOf(Object object) {
189         final Predicate<Field> hasMockAnnotation = field -> field.getAnnotation(Mock.class) != null;
190         final Predicate<Field> hasInjectMocksAnnotation = field -> field.getAnnotation(InjectMocks.class) != null;
191
192         return Arrays.stream(FieldUtils.getAllFields(object.getClass()))
193             .filter(hasMockAnnotation.or(hasInjectMocksAnnotation))
194             .collect(toList());
195     }
196
197     /**
198      * Calls MockitoAnnotations.initMocks after nullifying any field which is annotated @Mocke or @InjectMock.
199      * This makes a "hard rest" to any mocked state or instance. Expected to be invoked between any @Tests in class, by
200      * being called in TestNG's @BeforeMethod (or equivalently JUnit's @BeforeTest).
201      */
202     public static void initMockitoMocks(Object testClass) {
203         for (Field field : allMockitoFieldsOf(testClass)) {
204             try {
205                 // Write null to fields
206                 FieldUtils.writeField(field, testClass, null, true);
207             } catch (ReflectiveOperationException e) {
208                 ExceptionUtils.rethrow(e);
209             }
210         }
211
212         MockitoAnnotations.initMocks(testClass);
213     }
214
215     /**
216      * Sets each String property with a value equal to the name of
217      * the property; e.g.: { name: "name", city: "city" }
218      * @param object
219      * @param <T>
220      * @return The modified object
221      */
222     public static <T> T setStringsInStringProperties(T object) {
223         try {
224             final List<String> stringFields = allStringPropertiesOf(object);
225
226             BeanUtils.populate(object, stringFields.stream()
227                 .collect(toMap(identity(), identity())));
228
229             return object;
230         } catch (Exception e) {
231             throw new RuntimeException(e);
232         }
233     }
234
235     public static void registerCloudConfigurationValueGenerator() {
236         BeanMatchers.registerValueGenerator(() -> new CloudConfiguration(
237                 randomAlphabetic(7), randomAlphabetic(7), randomAlphabetic(7)
238             ), CloudConfiguration.class);
239     }
240
241     public static OngoingStubbing<InputStream> mockGetRawBodyWithStringBody(HttpResponse<String> httpResponse, String body) {
242         try {
243             return when(httpResponse.getRawBody()).thenReturn(IOUtils.toInputStream(body, StandardCharsets.UTF_8.name()));
244         } catch (IOException e) {
245             ExceptionUtils.rethrow(e);
246         }
247         return null; //never shall get here
248     }
249
250     public static HttpResponse<String> createTestHttpResponse(int statusCode, String entity) throws Exception {
251         HttpResponseFactory factory = new DefaultHttpResponseFactory();
252         org.apache.http.HttpResponse response = factory.newHttpResponse(new BasicStatusLine(HTTP_1_1, statusCode, null), null);
253         if (entity != null) {
254             response.setEntity(new StringEntity(entity));
255         }
256         return new HttpResponse<>(response, String.class, null);
257     }
258
259     public static <T> HttpResponse<T> createTestHttpResponse(int statusCode, T entity, final Class<T> entityClass) throws Exception {
260         HttpResponseFactory factory = new DefaultHttpResponseFactory();
261         org.apache.http.HttpResponse response = factory.newHttpResponse(new BasicStatusLine(HTTP_1_1, statusCode, null), null);
262         if (entity != null) {
263             InputStream inputStream = IOUtils.toInputStream(JACKSON_OBJECT_MAPPER.writeValueAsString(entity), StandardCharsets.UTF_8.name());
264             response.setEntity(new InputStreamEntity(inputStream));
265         }
266         return new HttpResponse(response, entityClass, JOSHWORKS_JACKSON_OBJECT_MAPPER);
267     }
268
269
270     public static class JavaxRsClientMocks {
271         private final javax.ws.rs.client.Client fakeClient;
272         private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
273         private final javax.ws.rs.client.Invocation fakeInvocation;
274         private final Response fakeResponse;
275
276         public javax.ws.rs.client.Client getFakeClient() {
277             return fakeClient;
278         }
279
280         public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
281             return fakeBuilder;
282         }
283
284         public Response getFakeResponse() {
285             return fakeResponse;
286         }
287
288         public JavaxRsClientMocks() {
289             final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());
290
291             fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
292             fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
293             fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings);
294             fakeResponse = mock(Response.class, mockSettings);
295             final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);
296
297             TriesToReturnMockByType.setAvailableMocks(
298                     fakeClient,
299                     fakeWebTarget,
300                     fakeBuilder,
301                     fakeInvocation,
302                     fakeResponse
303             );
304             Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
305             Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
306             Mockito.when(fakeResponse.getStatus()).thenReturn(200);
307             Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
308             Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
309             Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{}));
310             Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null);
311         }
312     }
313
314     /*
315        inspired out from newer Mockito version
316         returns a mock from given list if it's a matching return-type
317     */
318     private static class TriesToReturnMockByType implements Answer<Object>, Serializable {
319         private final Answer<Object> defaultReturn = RETURNS_DEFAULTS;
320         private static List<Object> availableMocks = ImmutableList.of();
321
322         static void setAvailableMocks(Object... mocks) {
323             availableMocks = ImmutableList.copyOf(mocks);
324         }
325
326         public Object answer(InvocationOnMock invocation) throws Throwable {
327             Class<?> methodReturnType = invocation.getMethod().getReturnType();
328
329             return availableMocks.stream()
330                     .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
331                     //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
332                     .findFirst()
333                     .orElse(defaultReturn.answer(invocation));
334         }
335     }
336
337
338     //The method mocks only some methods used in my case
339     //You may add some other when for your test here
340     public static Response mockResponseForJavaxClient(Client javaxClientMock) {
341         Response  mockResponse = mock(Response.class);
342         WebTarget webTarget = mock(WebTarget.class);
343         Invocation.Builder builder = mock(Invocation.Builder.class);
344         when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget);
345         when(webTarget.path(any())).thenReturn(webTarget);
346         when(webTarget.request(any(MediaType.class))).thenReturn(builder);
347         when(builder.headers(any())).thenReturn(builder);
348         when(builder.header(any(), any())).thenReturn(builder);
349         when(builder.get()).thenReturn(mockResponse);
350         return mockResponse;
351     }
352
353
354     public interface Test {
355
356         void apply() throws AsdcCatalogException;
357     }
358
359     public static void testWithSystemProperty(String key, String value, Test test) throws Exception {
360         SystemProperties systemProperties = new SystemProperties();
361         //use reflection to invoke protected method
362         Environment originalEnvironment = (Environment) MethodUtils
363             .invokeMethod(systemProperties, true, "getEnvironment");
364
365         try {
366             Environment environment = mock(Environment.class);
367             systemProperties.setEnvironment(environment);
368             when(environment.getRequiredProperty(key)).thenReturn(value);
369             when(environment.containsProperty(key)).thenReturn(true);
370             test.apply();
371         }
372         finally {
373             systemProperties.setEnvironment(originalEnvironment);
374         }
375     }
376
377     private static RandomStringGenerator generator = new RandomStringGenerator.Builder()
378             .withinRange('0', 'z')
379             .filteredBy(LETTERS, DIGITS)
380             .build();
381
382     public static String generateRandomAlphaNumeric(int length) {
383         return generator.generate(length);
384     }
385
386     @DataProvider
387     public static Object[][] trueAndFalse() {
388         return new Object[][]{{true}, {false}};
389     }
390
391 }