b4c7828bca50113e28cfc2d3501764a7a3dc84ee
[vid.git] / vid-app-common / src / test / java / org / onap / vid / testUtils / TestUtils.java
1 package org.onap.vid.testUtils;
2
3 import com.fasterxml.jackson.databind.DeserializationFeature;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import com.google.common.collect.ImmutableList;
6 import org.json.JSONArray;
7 import org.json.JSONObject;
8 import org.junit.Assert;
9 import org.mockito.MockSettings;
10 import org.mockito.Mockito;
11 import org.mockito.invocation.InvocationOnMock;
12 import org.mockito.stubbing.Answer;
13 import org.onap.vid.asdc.beans.Service;
14
15 import javax.ws.rs.core.GenericType;
16 import javax.ws.rs.core.Response;
17 import java.io.ByteArrayInputStream;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.Serializable;
21 import java.util.Iterator;
22 import java.util.List;
23
24 import static fj.parser.Parser.fail;
25 import static org.mockito.ArgumentMatchers.any;
26 import static org.mockito.ArgumentMatchers.eq;
27 import static org.mockito.Mockito.*;
28
29 /**
30  * Created by Oren on 6/7/17.
31  */
32 public class TestUtils {
33
34     /**
35      * 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.
36      * 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.
37      * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
38      * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
39      *
40      * @param expected JSON
41      * @param actual JSON
42      */
43     public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
44         if (expected == null || expected == JSONObject.NULL) {return;}
45
46         JSONObject expectedJSON = new JSONObject(expected);
47         JSONObject actualJSON = new JSONObject(actual);
48         Iterator<?> keys = expectedJSON.keys();
49
50         while( keys.hasNext() ) {
51             String key = (String)keys.next();
52             Object expectedValue = expectedJSON.get(key);
53             if (expectedValue == JSONObject.NULL){
54                 continue;
55             }
56
57             Object actualValue = actualJSON.get(key);
58
59             if (expectedValue instanceof JSONObject) {
60                 String expectedVal = expectedValue.toString();
61                 String actualVal = actualValue.toString();
62                 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
63             }
64             else if (expectedValue instanceof JSONArray) {
65                 if (actualValue instanceof JSONArray) {
66                     JSONArray expectedJSONArray = (JSONArray)expectedValue;
67                     JSONArray actualJSONArray = (JSONArray)actualValue;
68                     for (int i = 0; i < expectedJSONArray.length(); i++) {
69                         String expectedItem = expectedJSONArray.get(i).toString();
70                         String actualItem = actualJSONArray.get(i).toString();
71                         if (expectedValue instanceof JSONObject)
72                             assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
73                     }
74                 }
75                 else {
76                     fail("expected: " + expectedValue + " got:" + actualValue);
77                 }
78             }
79             else {
80                 Assert.assertEquals(expectedValue, actualValue);
81             }
82         }
83     }
84
85     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
86         return readJsonResourceFileAsObject(pathInResource, valueType, false);
87     }
88
89     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType, boolean ignoreUnknownProperties)
90             throws IOException {
91         ObjectMapper objectMapper = new ObjectMapper();
92         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, ignoreUnknownProperties);
93         return objectMapper.readValue(
94                 TestUtils.class.getResource(pathInResource),
95                 valueType);
96     }
97
98
99     public static class JavaxRsClientMocks {
100         private final javax.ws.rs.client.Client fakeClient;
101         private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
102         private final Response fakeResponse;
103
104         public javax.ws.rs.client.Client getFakeClient() {
105             return fakeClient;
106         }
107
108         public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
109             return fakeBuilder;
110         }
111
112         public Response getFakeResponse() {
113             return fakeResponse;
114         }
115
116         public JavaxRsClientMocks() {
117             final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());
118
119             fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
120             fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
121             fakeResponse = mock(Response.class, mockSettings);
122             final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);
123
124             TriesToReturnMockByType.setAvailableMocks(
125                     fakeClient,
126                     fakeWebTarget,
127                     fakeBuilder,
128                     fakeResponse
129             );
130
131             Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
132             Mockito.when(fakeBuilder.get(eq(InputStream.class))).thenReturn(new ByteArrayInputStream(new byte[]{}));
133             Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
134
135             Mockito.when(fakeResponse.getStatus()).thenReturn(200);
136             Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
137             Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
138         }
139     }
140
141     /*
142        inspired out from newer Mockito version
143         returns a mock from given list if it's a matching return-type
144     */
145     private static class TriesToReturnMockByType implements Answer<Object>, Serializable {
146         private final Answer<Object> defaultReturn = RETURNS_DEFAULTS;
147         private static List<Object> availableMocks = ImmutableList.of();
148
149         static void setAvailableMocks(Object... mocks) {
150             availableMocks = ImmutableList.copyOf(mocks);
151         }
152
153         public Object answer(InvocationOnMock invocation) throws Throwable {
154             Class<?> methodReturnType = invocation.getMethod().getReturnType();
155
156             return availableMocks.stream()
157                     .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
158                     //.peek(m -> System.out.println("found a mock: " + m.getClass().getName()))
159                     .findFirst()
160                     .orElse(defaultReturn.answer(invocation));
161         }
162     }
163 }