2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.testUtils;
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;
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;
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;
67 * Created by Oren on 6/7/17.
69 public class TestUtils {
71 private static final Logger logger = LogManager.getLogger(TestUtils.class);
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
79 * @param expected JSON
82 public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
83 if (expected == null || expected == JSONObject.NULL) {return;}
85 JSONObject expectedJSON = new JSONObject(expected);
86 JSONObject actualJSON = new JSONObject(actual);
87 Iterator<?> keys = expectedJSON.keys();
89 while( keys.hasNext() ) {
90 String key = (String)keys.next();
91 Object expectedValue = expectedJSON.get(key);
92 if (expectedValue == JSONObject.NULL){
96 Object actualValue = actualJSON.get(key);
98 if (expectedValue instanceof JSONObject) {
99 String expectedVal = expectedValue.toString();
100 String actualVal = actualValue.toString();
101 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
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);
115 fail("expected: " + expectedValue + " got:" + actualValue);
119 Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
124 public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
125 return readJsonResourceFileAsObject(pathInResource, valueType, false);
128 public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType, boolean ignoreUnknownProperties)
130 ObjectMapper objectMapper = new ObjectMapper();
131 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, ignoreUnknownProperties);
132 return objectMapper.readValue(
133 TestUtils.class.getResource(pathInResource),
137 public static String[] allPropertiesOf(Class<?> aClass) {
138 return Arrays.stream(getPropertyDescriptors(aClass))
139 .map(PropertyDescriptor::getDisplayName)
140 .toArray(String[]::new);
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)
151 * Sets each String property with a value equal to the name of
152 * the property; e.g.: { name: "name", city: "city" }
155 * @return The modified object
157 public static <T> T setStringsInStringProperties(T object) {
159 final List<String> stringFields = allStringPropertiesOf(object);
161 BeanUtils.populate(object, stringFields.stream()
162 .collect(toMap(identity(), identity())));
165 } catch (Exception e) {
166 throw new RuntimeException(e);
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;
177 public javax.ws.rs.client.Client getFakeClient() {
181 public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
185 public Response getFakeResponse() {
189 public JavaxRsClientMocks() {
190 final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());
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);
198 TriesToReturnMockByType.setAvailableMocks(
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);
216 inspired out from newer Mockito version
217 returns a mock from given list if it's a matching return-type
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();
223 static void setAvailableMocks(Object... mocks) {
224 availableMocks = ImmutableList.copyOf(mocks);
227 public Object answer(InvocationOnMock invocation) throws Throwable {
228 Class<?> methodReturnType = invocation.getMethod().getReturnType();
230 return availableMocks.stream()
231 .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
232 //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
234 .orElse(defaultReturn.answer(invocation));
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);
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);
260 SystemProperties systemProperties = new SystemProperties();
261 systemProperties.setEnvironment(mockEnvironment);
264 public static void resetSystemProperties() {
265 SystemProperties systemProperties = new SystemProperties();
266 systemProperties.setEnvironment(null);