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 org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors;
24 import static org.mockito.Matchers.any;
25 import static org.mockito.Mockito.RETURNS_DEFAULTS;
26 import static org.mockito.Mockito.mock;
27 import static org.mockito.Mockito.when;
28 import static org.mockito.Mockito.withSettings;
29 import static org.testng.Assert.fail;
31 import com.fasterxml.jackson.databind.DeserializationFeature;
32 import com.fasterxml.jackson.databind.ObjectMapper;
33 import com.google.common.collect.ImmutableList;
34 import java.beans.PropertyDescriptor;
35 import java.io.ByteArrayInputStream;
36 import java.io.IOException;
37 import java.io.InputStream;
38 import java.io.Serializable;
40 import java.util.Arrays;
41 import java.util.Iterator;
42 import java.util.List;
43 import javax.ws.rs.client.Client;
44 import javax.ws.rs.client.Invocation;
45 import javax.ws.rs.client.WebTarget;
46 import javax.ws.rs.core.GenericType;
47 import javax.ws.rs.core.MediaType;
48 import javax.ws.rs.core.Response;
49 import org.apache.log4j.LogManager;
50 import org.apache.log4j.Logger;
51 import org.json.JSONArray;
52 import org.json.JSONObject;
53 import org.junit.Assert;
54 import org.mockito.MockSettings;
55 import org.mockito.Mockito;
56 import org.mockito.invocation.InvocationOnMock;
57 import org.mockito.stubbing.Answer;
58 import org.onap.portalsdk.core.domain.support.DomainVo;
59 import org.onap.portalsdk.core.util.SystemProperties;
60 import org.onap.vid.asdc.beans.Service;
61 import org.springframework.mock.env.MockEnvironment;
64 * Created by Oren on 6/7/17.
66 public class TestUtils {
68 private static final Logger logger = LogManager.getLogger(TestUtils.class);
71 * 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.
72 * 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.
73 * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
74 * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
76 * @param expected JSON
79 public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
80 if (expected == null || expected == JSONObject.NULL) {return;}
82 JSONObject expectedJSON = new JSONObject(expected);
83 JSONObject actualJSON = new JSONObject(actual);
84 Iterator<?> keys = expectedJSON.keys();
86 while( keys.hasNext() ) {
87 String key = (String)keys.next();
88 Object expectedValue = expectedJSON.get(key);
89 if (expectedValue == JSONObject.NULL){
93 Object actualValue = actualJSON.get(key);
95 if (expectedValue instanceof JSONObject) {
96 String expectedVal = expectedValue.toString();
97 String actualVal = actualValue.toString();
98 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
100 else if (expectedValue instanceof JSONArray) {
101 if (actualValue instanceof JSONArray) {
102 JSONArray expectedJSONArray = (JSONArray)expectedValue;
103 JSONArray actualJSONArray = (JSONArray)actualValue;
104 for (int i = 0; i < expectedJSONArray.length(); i++) {
105 String expectedItem = expectedJSONArray.get(i).toString();
106 String actualItem = actualJSONArray.get(i).toString();
107 if (expectedValue instanceof JSONObject)
108 assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
112 fail("expected: " + expectedValue + " got:" + actualValue);
116 Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
121 public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
122 return readJsonResourceFileAsObject(pathInResource, valueType, false);
125 public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType, boolean ignoreUnknownProperties)
127 ObjectMapper objectMapper = new ObjectMapper();
128 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, ignoreUnknownProperties);
129 return objectMapper.readValue(
130 TestUtils.class.getResource(pathInResource),
134 public static String[] allPropertiesOf(Class<DomainVo> aClass) {
135 return Arrays.stream(getPropertyDescriptors(aClass))
136 .map(PropertyDescriptor::getDisplayName)
137 .toArray(String[]::new);
141 public static class JavaxRsClientMocks {
142 private final javax.ws.rs.client.Client fakeClient;
143 private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
144 private final javax.ws.rs.client.Invocation fakeInvocation;
145 private final Response fakeResponse;
147 public javax.ws.rs.client.Client getFakeClient() {
151 public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
155 public Response getFakeResponse() {
159 public JavaxRsClientMocks() {
160 final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());
162 fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
163 fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
164 fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings);
165 fakeResponse = mock(Response.class, mockSettings);
166 final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);
168 TriesToReturnMockByType.setAvailableMocks(
175 Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
176 Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
177 Mockito.when(fakeResponse.getStatus()).thenReturn(200);
178 Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
179 Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
180 Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{}));
181 Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null);
186 inspired out from newer Mockito version
187 returns a mock from given list if it's a matching return-type
189 private static class TriesToReturnMockByType implements Answer<Object>, Serializable {
190 private final Answer<Object> defaultReturn = RETURNS_DEFAULTS;
191 private static List<Object> availableMocks = ImmutableList.of();
193 static void setAvailableMocks(Object... mocks) {
194 availableMocks = ImmutableList.copyOf(mocks);
197 public Object answer(InvocationOnMock invocation) throws Throwable {
198 Class<?> methodReturnType = invocation.getMethod().getReturnType();
200 return availableMocks.stream()
201 .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
202 //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
204 .orElse(defaultReturn.answer(invocation));
209 //The method mocks only some methods used in my case
210 //You may add some other when for your test here
211 public static Response mockResponseForJavaxClient(Client javaxClientMock) {
212 Response mockResponse = mock(Response.class);
213 WebTarget webTarget = mock(WebTarget.class);
214 Invocation.Builder builder = mock(Invocation.Builder.class);
215 when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget);
216 when(webTarget.path(any())).thenReturn(webTarget);
217 when(webTarget.request(any(MediaType.class))).thenReturn(builder);
218 when(builder.headers(any())).thenReturn(builder);
219 when(builder.header(any(), any())).thenReturn(builder);
220 when(builder.get()).thenReturn(mockResponse);
225 //Please use resetSystemProperties after using this method, so other test won't be affected
226 public static void mockSystemPropertyWithKeyValue(String key, String value) {
227 MockEnvironment mockEnvironment = new MockEnvironment();
228 mockEnvironment.setProperty(key, value);
230 SystemProperties systemProperties = new SystemProperties();
231 systemProperties.setEnvironment(mockEnvironment);
234 public static void resetSystemProperties() {
235 SystemProperties systemProperties = new SystemProperties();
236 systemProperties.setEnvironment(null);