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