Implant vid-app-common org.onap.vid.job (main and test)
[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.mockito.Matchers.any;
32 import static org.mockito.Mockito.RETURNS_DEFAULTS;
33 import static org.mockito.Mockito.mock;
34 import static org.mockito.Mockito.when;
35 import static org.mockito.Mockito.withSettings;
36 import static org.testng.Assert.fail;
37
38 import com.fasterxml.jackson.databind.DeserializationFeature;
39 import com.fasterxml.jackson.databind.ObjectMapper;
40 import com.google.code.beanmatchers.BeanMatchers;
41 import com.google.common.collect.ImmutableList;
42 import java.beans.PropertyDescriptor;
43 import java.io.ByteArrayInputStream;
44 import java.io.IOException;
45 import java.io.InputStream;
46 import java.io.Serializable;
47 import java.net.URI;
48 import java.util.Arrays;
49 import java.util.Iterator;
50 import java.util.List;
51 import javax.ws.rs.client.Client;
52 import javax.ws.rs.client.Invocation;
53 import javax.ws.rs.client.WebTarget;
54 import javax.ws.rs.core.GenericType;
55 import javax.ws.rs.core.MediaType;
56 import javax.ws.rs.core.Response;
57 import org.apache.commons.beanutils.BeanUtils;
58 import org.apache.commons.io.IOUtils;
59 import org.apache.commons.lang3.reflect.MethodUtils;
60 import org.apache.commons.text.RandomStringGenerator;
61 import org.apache.log4j.LogManager;
62 import org.apache.log4j.Logger;
63 import org.json.JSONArray;
64 import org.json.JSONObject;
65 import org.junit.Assert;
66 import org.mockito.MockSettings;
67 import org.mockito.Mockito;
68 import org.mockito.invocation.InvocationOnMock;
69 import org.mockito.stubbing.Answer;
70 import org.onap.portalsdk.core.util.SystemProperties;
71 import org.onap.vid.asdc.beans.Service;
72 import org.onap.vid.mso.model.CloudConfiguration;
73 import org.springframework.core.env.Environment;
74 import org.testng.annotations.DataProvider;
75
76 /**
77  * Created by Oren on 6/7/17.
78  */
79 public class TestUtils {
80
81     private static final Logger logger = LogManager.getLogger(TestUtils.class);
82
83     /**
84      * 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.
85      * 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.
86      * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
87      * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
88      *
89      * @param expected JSON
90      * @param actual JSON
91      */
92     public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
93         if (expected == null || expected == JSONObject.NULL) {return;}
94
95         JSONObject expectedJSON = new JSONObject(expected);
96         JSONObject actualJSON = new JSONObject(actual);
97         Iterator<?> keys = expectedJSON.keys();
98
99         while( keys.hasNext() ) {
100             String key = (String)keys.next();
101             Object expectedValue = expectedJSON.get(key);
102             if (expectedValue == JSONObject.NULL){
103                 continue;
104             }
105
106             Object actualValue = actualJSON.get(key);
107
108             if (expectedValue instanceof JSONObject) {
109                 String expectedVal = expectedValue.toString();
110                 String actualVal = actualValue.toString();
111                 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
112             }
113             else if (expectedValue instanceof JSONArray) {
114                 if (actualValue instanceof JSONArray) {
115                     JSONArray expectedJSONArray = (JSONArray)expectedValue;
116                     JSONArray actualJSONArray = (JSONArray)actualValue;
117                     for (int i = 0; i < expectedJSONArray.length(); i++) {
118                         String expectedItem = expectedJSONArray.get(i).toString();
119                         String actualItem = actualJSONArray.get(i).toString();
120                         if (expectedValue instanceof JSONObject)
121                             assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
122                     }
123                 }
124                 else {
125                     fail("expected: " + expectedValue + " got:" + actualValue);
126                 }
127             }
128             else {
129                 Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
130             }
131         }
132     }
133
134     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
135         return readJsonResourceFileAsObject(pathInResource, valueType, false);
136     }
137
138     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType,
139         boolean failOnUnknownProperties)
140         throws IOException {
141         ObjectMapper objectMapper = jacksonObjectMapper()
142             .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties);
143         return objectMapper.readValue(
144             TestUtils.class.getResource(pathInResource),
145             valueType);
146     }
147
148     public static String readFileAsString(String pathInResource) {
149         try {
150             return IOUtils.toString(TestUtils.class.getResource(pathInResource), "UTF-8");
151         } catch (IOException e) {
152             throw new RuntimeException(e);
153         }
154     }
155
156     public static String[] allPropertiesOf(Class<?> aClass) {
157         return Arrays.stream(getPropertyDescriptors(aClass))
158             .map(PropertyDescriptor::getDisplayName)
159             .toArray(String[]::new);
160     }
161
162     private static <T> List<String> allStringPropertiesOf(T object) {
163         return Arrays.stream(getPropertyDescriptors(object.getClass()))
164             .filter(descriptor -> descriptor.getPropertyType().isAssignableFrom(String.class))
165             .map(PropertyDescriptor::getDisplayName)
166             .collect(toList());
167     }
168
169     /**
170      * Sets each String property with a value equal to the name of
171      * the property; e.g.: { name: "name", city: "city" }
172      * @param object
173      * @param <T>
174      * @return The modified object
175      */
176     public static <T> T setStringsInStringProperties(T object) {
177         try {
178             final List<String> stringFields = allStringPropertiesOf(object);
179
180             BeanUtils.populate(object, stringFields.stream()
181                 .collect(toMap(identity(), identity())));
182
183             return object;
184         } catch (Exception e) {
185             throw new RuntimeException(e);
186         }
187     }
188
189     public static void registerCloudConfigurationValueGenerator() {
190         BeanMatchers.registerValueGenerator(() -> new CloudConfiguration(
191                 randomAlphabetic(7), randomAlphabetic(7), randomAlphabetic(7)
192             ), CloudConfiguration.class);
193     }
194
195
196     public static class JavaxRsClientMocks {
197         private final javax.ws.rs.client.Client fakeClient;
198         private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
199         private final javax.ws.rs.client.Invocation fakeInvocation;
200         private final Response fakeResponse;
201
202         public javax.ws.rs.client.Client getFakeClient() {
203             return fakeClient;
204         }
205
206         public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
207             return fakeBuilder;
208         }
209
210         public Response getFakeResponse() {
211             return fakeResponse;
212         }
213
214         public JavaxRsClientMocks() {
215             final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());
216
217             fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
218             fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
219             fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings);
220             fakeResponse = mock(Response.class, mockSettings);
221             final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);
222
223             TriesToReturnMockByType.setAvailableMocks(
224                     fakeClient,
225                     fakeWebTarget,
226                     fakeBuilder,
227                     fakeInvocation,
228                     fakeResponse
229             );
230             Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
231             Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
232             Mockito.when(fakeResponse.getStatus()).thenReturn(200);
233             Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
234             Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
235             Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{}));
236             Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null);
237         }
238     }
239
240     /*
241        inspired out from newer Mockito version
242         returns a mock from given list if it's a matching return-type
243     */
244     private static class TriesToReturnMockByType implements Answer<Object>, Serializable {
245         private final Answer<Object> defaultReturn = RETURNS_DEFAULTS;
246         private static List<Object> availableMocks = ImmutableList.of();
247
248         static void setAvailableMocks(Object... mocks) {
249             availableMocks = ImmutableList.copyOf(mocks);
250         }
251
252         public Object answer(InvocationOnMock invocation) throws Throwable {
253             Class<?> methodReturnType = invocation.getMethod().getReturnType();
254
255             return availableMocks.stream()
256                     .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
257                     //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
258                     .findFirst()
259                     .orElse(defaultReturn.answer(invocation));
260         }
261     }
262
263
264     //The method mocks only some methods used in my case
265     //You may add some other when for your test here
266     public static Response mockResponseForJavaxClient(Client javaxClientMock) {
267         Response  mockResponse = mock(Response.class);
268         WebTarget webTarget = mock(WebTarget.class);
269         Invocation.Builder builder = mock(Invocation.Builder.class);
270         when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget);
271         when(webTarget.path(any())).thenReturn(webTarget);
272         when(webTarget.request(any(MediaType.class))).thenReturn(builder);
273         when(builder.headers(any())).thenReturn(builder);
274         when(builder.header(any(), any())).thenReturn(builder);
275         when(builder.get()).thenReturn(mockResponse);
276         return mockResponse;
277     }
278
279
280     public interface Test {
281
282         void apply();
283     }
284
285     public static void testWithSystemProperty(String key, String value, Test test) throws Exception {
286         SystemProperties systemProperties = new SystemProperties();
287         //use reflection to invoke protected method
288         Environment originalEnvironment = (Environment) MethodUtils
289             .invokeMethod(systemProperties, true, "getEnvironment");
290
291         try {
292             Environment environment = mock(Environment.class);
293             systemProperties.setEnvironment(environment);
294             when(environment.getRequiredProperty(key)).thenReturn(value);
295             when(environment.containsProperty(key)).thenReturn(true);
296             test.apply();
297         }
298         finally {
299             systemProperties.setEnvironment(originalEnvironment);
300         }
301     }
302
303     private static RandomStringGenerator generator = new RandomStringGenerator.Builder()
304             .withinRange('0', 'z')
305             .filteredBy(LETTERS, DIGITS)
306             .build();
307
308     public static String generateRandomAlphaNumeric(int length) {
309         return generator.generate(length);
310     }
311
312     @DataProvider
313     public static Object[][] trueAndFalse() {
314         return new Object[][]{{true}, {false}};
315     }
316
317 }