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 com.fasterxml.jackson.databind.DeserializationFeature;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.google.common.collect.ImmutableList;
26 import org.apache.log4j.LogManager;
27 import org.apache.log4j.Logger;
28 import org.json.JSONArray;
29 import org.json.JSONObject;
30 import org.junit.Assert;
31 import org.mockito.MockSettings;
32 import org.mockito.Mockito;
33 import org.mockito.invocation.InvocationOnMock;
34 import org.mockito.stubbing.Answer;
35 import org.onap.portalsdk.core.util.SystemProperties;
36 import org.onap.vid.asdc.beans.Service;
37 import org.springframework.mock.env.MockEnvironment;
39 import javax.ws.rs.client.Client;
40 import javax.ws.rs.client.Invocation;
41 import javax.ws.rs.client.WebTarget;
42 import javax.ws.rs.core.GenericType;
43 import javax.ws.rs.core.MediaType;
44 import javax.ws.rs.core.Response;
45 import java.io.ByteArrayInputStream;
46 import java.io.IOException;
47 import java.io.InputStream;
48 import java.io.Serializable;
50 import java.util.Iterator;
51 import java.util.List;
53 import static fj.parser.Parser.fail;
54 import static org.mockito.Matchers.any;
55 import static org.mockito.Mockito.*;
58 * Created by Oren on 6/7/17.
60 public class TestUtils {
62 private static final Logger logger = LogManager.getLogger(TestUtils.class);
65 * 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.
66 * 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.
67 * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
68 * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
70 * @param expected JSON
73 public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
74 if (expected == null || expected == JSONObject.NULL) {return;}
76 JSONObject expectedJSON = new JSONObject(expected);
77 JSONObject actualJSON = new JSONObject(actual);
78 Iterator<?> keys = expectedJSON.keys();
80 while( keys.hasNext() ) {
81 String key = (String)keys.next();
82 Object expectedValue = expectedJSON.get(key);
83 if (expectedValue == JSONObject.NULL){
87 Object actualValue = actualJSON.get(key);
89 if (expectedValue instanceof JSONObject) {
90 String expectedVal = expectedValue.toString();
91 String actualVal = actualValue.toString();
92 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
94 else if (expectedValue instanceof JSONArray) {
95 if (actualValue instanceof JSONArray) {
96 JSONArray expectedJSONArray = (JSONArray)expectedValue;
97 JSONArray actualJSONArray = (JSONArray)actualValue;
98 for (int i = 0; i < expectedJSONArray.length(); i++) {
99 String expectedItem = expectedJSONArray.get(i).toString();
100 String actualItem = actualJSONArray.get(i).toString();
101 if (expectedValue instanceof JSONObject)
102 assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
106 fail("expected: " + expectedValue + " got:" + actualValue);
110 Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
115 public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
116 return readJsonResourceFileAsObject(pathInResource, valueType, false);
119 public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType, boolean ignoreUnknownProperties)
121 ObjectMapper objectMapper = new ObjectMapper();
122 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, ignoreUnknownProperties);
123 return objectMapper.readValue(
124 TestUtils.class.getResource(pathInResource),
129 public static class JavaxRsClientMocks {
130 private final javax.ws.rs.client.Client fakeClient;
131 private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
132 private final javax.ws.rs.client.Invocation fakeInvocation;
133 private final Response fakeResponse;
135 public javax.ws.rs.client.Client getFakeClient() {
139 public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
143 public Response getFakeResponse() {
147 public JavaxRsClientMocks() {
148 final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());
150 fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
151 fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
152 fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings);
153 fakeResponse = mock(Response.class, mockSettings);
154 final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);
156 TriesToReturnMockByType.setAvailableMocks(
163 Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
164 Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
165 Mockito.when(fakeResponse.getStatus()).thenReturn(200);
166 Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
167 Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
168 Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{}));
169 Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null);
174 inspired out from newer Mockito version
175 returns a mock from given list if it's a matching return-type
177 private static class TriesToReturnMockByType implements Answer<Object>, Serializable {
178 private final Answer<Object> defaultReturn = RETURNS_DEFAULTS;
179 private static List<Object> availableMocks = ImmutableList.of();
181 static void setAvailableMocks(Object... mocks) {
182 availableMocks = ImmutableList.copyOf(mocks);
185 public Object answer(InvocationOnMock invocation) throws Throwable {
186 Class<?> methodReturnType = invocation.getMethod().getReturnType();
188 return availableMocks.stream()
189 .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
190 //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
192 .orElse(defaultReturn.answer(invocation));
197 //The method mocks only some methods used in my case
198 //You may add some other when for your test here
199 public static Response mockResponseForJavaxClient(Client javaxClientMock) {
200 Response mockResponse = mock(Response.class);
201 WebTarget webTarget = mock(WebTarget.class);
202 Invocation.Builder builder = mock(Invocation.Builder.class);
203 when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget);
204 when(webTarget.path(any())).thenReturn(webTarget);
205 when(webTarget.request(any(MediaType.class))).thenReturn(builder);
206 when(builder.headers(any())).thenReturn(builder);
207 when(builder.header(any(), any())).thenReturn(builder);
208 when(builder.get()).thenReturn(mockResponse);
213 //Please use resetSystemProperties after using this method, so other test won't be affected
214 public static void mockSystemPropertyWithKeyValue(String key, String value) {
215 MockEnvironment mockEnvironment = new MockEnvironment();
216 mockEnvironment.setProperty(key, value);
218 SystemProperties systemProperties = new SystemProperties();
219 systemProperties.setEnvironment(mockEnvironment);
222 public static void resetSystemProperties() {
223 SystemProperties systemProperties = new SystemProperties();
224 systemProperties.setEnvironment(null);