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