aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
blob: 756d17534c58d7974e2ece29cac32e6016bd4f1e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*-
 * ============LICENSE_START=======================================================
 * VID
 * ================================================================================
 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.vid.testUtils;

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.RETURNS_DEFAULTS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;
import static org.testng.Assert.fail;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.mockito.MockSettings;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.asdc.beans.Service;
import org.springframework.core.env.Environment;
import org.springframework.mock.env.MockEnvironment;

/**
 * Created by Oren on 6/7/17.
 */
public class TestUtils {

    private static final Logger logger = LogManager.getLogger(TestUtils.class);

    /**
     * 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.
     * 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.
     * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
     * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
     *
     * @param expected JSON
     * @param actual JSON
     */
    public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
        if (expected == null || expected == JSONObject.NULL) {return;}

        JSONObject expectedJSON = new JSONObject(expected);
        JSONObject actualJSON = new JSONObject(actual);
        Iterator<?> keys = expectedJSON.keys();

        while( keys.hasNext() ) {
            String key = (String)keys.next();
            Object expectedValue = expectedJSON.get(key);
            if (expectedValue == JSONObject.NULL){
                continue;
            }

            Object actualValue = actualJSON.get(key);

            if (expectedValue instanceof JSONObject) {
                String expectedVal = expectedValue.toString();
                String actualVal = actualValue.toString();
                assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
            }
            else if (expectedValue instanceof JSONArray) {
                if (actualValue instanceof JSONArray) {
                    JSONArray expectedJSONArray = (JSONArray)expectedValue;
                    JSONArray actualJSONArray = (JSONArray)actualValue;
                    for (int i = 0; i < expectedJSONArray.length(); i++) {
                        String expectedItem = expectedJSONArray.get(i).toString();
                        String actualItem = actualJSONArray.get(i).toString();
                        if (expectedValue instanceof JSONObject)
                            assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
                    }
                }
                else {
                    fail("expected: " + expectedValue + " got:" + actualValue);
                }
            }
            else {
                Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
            }
        }
    }

    public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
        return readJsonResourceFileAsObject(pathInResource, valueType, false);
    }

    public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType, boolean ignoreUnknownProperties)
            throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, ignoreUnknownProperties);
        return objectMapper.readValue(
                TestUtils.class.getResource(pathInResource),
                valueType);
    }

    public static String[] allPropertiesOf(Class<?> aClass) {
        return Arrays.stream(getPropertyDescriptors(aClass))
            .map(PropertyDescriptor::getDisplayName)
            .toArray(String[]::new);
    }

    private static <T> List<String> allStringPropertiesOf(T object) {
        return Arrays.stream(getPropertyDescriptors(object.getClass()))
            .filter(descriptor -> descriptor.getPropertyType().isAssignableFrom(String.class))
            .map(PropertyDescriptor::getDisplayName)
            .collect(toList());
    }

    /**
     * Sets each String property with a value equal to the name of
     * the property; e.g.: { name: "name", city: "city" }
     * @param object
     * @param <T>
     * @return The modified object
     */
    public static <T> T setStringsInStringProperties(T object) {
        try {
            final List<String> stringFields = allStringPropertiesOf(object);

            BeanUtils.populate(object, stringFields.stream()
                .collect(toMap(identity(), identity())));

            return object;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static class JavaxRsClientMocks {
        private final javax.ws.rs.client.Client fakeClient;
        private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
        private final javax.ws.rs.client.Invocation fakeInvocation;
        private final Response fakeResponse;

        public javax.ws.rs.client.Client getFakeClient() {
            return fakeClient;
        }

        public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
            return fakeBuilder;
        }

        public Response getFakeResponse() {
            return fakeResponse;
        }

        public JavaxRsClientMocks() {
            final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());

            fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
            fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
            fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings);
            fakeResponse = mock(Response.class, mockSettings);
            final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);

            TriesToReturnMockByType.setAvailableMocks(
                    fakeClient,
                    fakeWebTarget,
                    fakeBuilder,
                    fakeInvocation,
                    fakeResponse
            );
            Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
            Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
            Mockito.when(fakeResponse.getStatus()).thenReturn(200);
            Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
            Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
            Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{}));
            Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null);
        }
    }

    /*
       inspired out from newer Mockito version
        returns a mock from given list if it's a matching return-type
    */
    private static class TriesToReturnMockByType implements Answer<Object>, Serializable {
        private final Answer<Object> defaultReturn = RETURNS_DEFAULTS;
        private static List<Object> availableMocks = ImmutableList.of();

        static void setAvailableMocks(Object... mocks) {
            availableMocks = ImmutableList.copyOf(mocks);
        }

        public Object answer(InvocationOnMock invocation) throws Throwable {
            Class<?> methodReturnType = invocation.getMethod().getReturnType();

            return availableMocks.stream()
                    .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
                    //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
                    .findFirst()
                    .orElse(defaultReturn.answer(invocation));
        }
    }


    //The method mocks only some methods used in my case
    //You may add some other when for your test here
    public static Response mockResponseForJavaxClient(Client javaxClientMock) {
        Response  mockResponse = mock(Response.class);
        WebTarget webTarget = mock(WebTarget.class);
        Invocation.Builder builder = mock(Invocation.Builder.class);
        when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget);
        when(webTarget.path(any())).thenReturn(webTarget);
        when(webTarget.request(any(MediaType.class))).thenReturn(builder);
        when(builder.headers(any())).thenReturn(builder);
        when(builder.header(any(), any())).thenReturn(builder);
        when(builder.get()).thenReturn(mockResponse);
        return mockResponse;
    }


    public interface Test {

        void apply();
    }

    public static void testWithSystemProperty(String key, String value, Test test) throws Exception {
        SystemProperties systemProperties = new SystemProperties();
        //use reflection to invoke protected method
        Environment originalEnvironment = (Environment) MethodUtils
            .invokeMethod(systemProperties, true, "getEnvironment");

        try {
            Environment environment = mock(Environment.class);
            systemProperties.setEnvironment(environment);
            when(environment.getRequiredProperty(key)).thenReturn(value);
            when(environment.containsProperty(key)).thenReturn(true);
            test.apply();
        }
        finally {
            systemProperties.setEnvironment(originalEnvironment);
        }
    }

}