update MSO configuration URL
[vid.git] / vid-app-common / src / test / java / org / onap / vid / testUtils / TestUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.vid.testUtils;
22
23 import static com.fasterxml.jackson.module.kotlin.ExtensionsKt.jacksonObjectMapper;
24 import static java.util.function.Function.identity;
25 import static java.util.stream.Collectors.toList;
26 import static java.util.stream.Collectors.toMap;
27 import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors;
28 import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
29 import static org.apache.commons.text.CharacterPredicates.DIGITS;
30 import static org.apache.commons.text.CharacterPredicates.LETTERS;
31 import static org.apache.http.HttpVersion.HTTP_1_1;
32 import static org.mockito.ArgumentMatchers.any;
33 import static org.mockito.Mockito.RETURNS_DEFAULTS;
34 import static org.mockito.Mockito.mock;
35 import static org.mockito.Mockito.when;
36 import static org.mockito.Mockito.withSettings;
37 import static org.testng.Assert.fail;
38
39 import com.fasterxml.jackson.databind.DeserializationFeature;
40 import com.fasterxml.jackson.databind.ObjectMapper;
41 import com.google.code.beanmatchers.BeanMatchers;
42 import com.google.common.collect.ImmutableList;
43 import io.joshworks.restclient.http.HttpResponse;
44 import java.beans.PropertyDescriptor;
45 import java.io.ByteArrayInputStream;
46 import java.io.IOException;
47 import java.io.InputStream;
48 import java.io.Serializable;
49 import java.net.URI;
50 import java.nio.charset.StandardCharsets;
51 import java.util.Arrays;
52 import java.util.Iterator;
53 import java.util.List;
54 import javax.ws.rs.client.Client;
55 import javax.ws.rs.client.Invocation;
56 import javax.ws.rs.client.WebTarget;
57 import javax.ws.rs.core.GenericType;
58 import javax.ws.rs.core.MediaType;
59 import javax.ws.rs.core.Response;
60 import org.apache.commons.beanutils.BeanUtils;
61 import org.apache.commons.io.IOUtils;
62 import org.apache.commons.lang3.exception.ExceptionUtils;
63 import org.apache.commons.lang3.reflect.MethodUtils;
64 import org.apache.commons.text.RandomStringGenerator;
65 import org.apache.http.HttpResponseFactory;
66 import org.apache.http.entity.StringEntity;
67 import org.apache.http.impl.DefaultHttpResponseFactory;
68 import org.apache.http.message.BasicStatusLine;
69 import org.apache.log4j.LogManager;
70 import org.apache.log4j.Logger;
71 import org.json.JSONArray;
72 import org.json.JSONObject;
73 import org.junit.Assert;
74 import org.mockito.MockSettings;
75 import org.mockito.Mockito;
76 import org.mockito.invocation.InvocationOnMock;
77 import org.mockito.stubbing.Answer;
78 import org.mockito.stubbing.OngoingStubbing;
79 import org.onap.portalsdk.core.util.SystemProperties;
80 import org.onap.vid.asdc.AsdcCatalogException;
81 import org.onap.vid.asdc.beans.Service;
82 import org.onap.vid.mso.model.CloudConfiguration;
83 import org.springframework.core.env.Environment;
84 import org.testng.annotations.DataProvider;
85
86 /**
87  * Created by Oren on 6/7/17.
88  */
89 public class TestUtils {
90
91     private static final Logger logger = LogManager.getLogger(TestUtils.class);
92
93     /**
94      * 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.
95      * 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.
96      * For example : For JSON expected = {a:null} and actual {a:3} the test will pass
97      * Other example : For JSON expected = {a:3} and actual {a:null} the test will fail
98      *
99      * @param expected JSON
100      * @param actual JSON
101      */
102     public static void assertJsonStringEqualsIgnoreNulls(String expected, String actual) {
103         if (expected == null || expected == JSONObject.NULL) {return;}
104
105         JSONObject expectedJSON = new JSONObject(expected);
106         JSONObject actualJSON = new JSONObject(actual);
107         Iterator<?> keys = expectedJSON.keys();
108
109         while( keys.hasNext() ) {
110             String key = (String)keys.next();
111             Object expectedValue = expectedJSON.get(key);
112             if (expectedValue == JSONObject.NULL){
113                 continue;
114             }
115
116             Object actualValue = actualJSON.get(key);
117
118             if (expectedValue instanceof JSONObject) {
119                 String expectedVal = expectedValue.toString();
120                 String actualVal = actualValue.toString();
121                 assertJsonStringEqualsIgnoreNulls(expectedVal, actualVal);
122             }
123             else if (expectedValue instanceof JSONArray) {
124                 if (actualValue instanceof JSONArray) {
125                     JSONArray expectedJSONArray = (JSONArray)expectedValue;
126                     JSONArray actualJSONArray = (JSONArray)actualValue;
127                     for (int i = 0; i < expectedJSONArray.length(); i++) {
128                         String expectedItem = expectedJSONArray.get(i).toString();
129                         String actualItem = actualJSONArray.get(i).toString();
130                         if (expectedValue instanceof JSONObject)
131                             assertJsonStringEqualsIgnoreNulls(expectedItem, actualItem);
132                     }
133                 }
134                 else {
135                     fail("expected: " + expectedValue + " got:" + actualValue);
136                 }
137             }
138             else {
139                 Assert.assertEquals("assertion fail for key:"+key, expectedValue, actualValue);
140             }
141         }
142     }
143
144     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType) throws IOException {
145         return readJsonResourceFileAsObject(pathInResource, valueType, false);
146     }
147
148     public static <T> T readJsonResourceFileAsObject(String pathInResource, Class<T> valueType,
149         boolean failOnUnknownProperties)
150         throws IOException {
151         ObjectMapper objectMapper = jacksonObjectMapper()
152             .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties);
153         return objectMapper.readValue(
154             TestUtils.class.getResource(pathInResource),
155             valueType);
156     }
157
158     public static String readFileAsString(String pathInResource) {
159         try {
160             return IOUtils.toString(TestUtils.class.getResource(pathInResource), "UTF-8");
161         } catch (IOException e) {
162             throw new RuntimeException(e);
163         }
164     }
165
166     public static String[] allPropertiesOf(Class<?> aClass) {
167         return Arrays.stream(getPropertyDescriptors(aClass))
168             .map(PropertyDescriptor::getDisplayName)
169             .toArray(String[]::new);
170     }
171
172     private static <T> List<String> allStringPropertiesOf(T object) {
173         return Arrays.stream(getPropertyDescriptors(object.getClass()))
174             .filter(descriptor -> descriptor.getPropertyType().isAssignableFrom(String.class))
175             .map(PropertyDescriptor::getDisplayName)
176             .collect(toList());
177     }
178
179     /**
180      * Sets each String property with a value equal to the name of
181      * the property; e.g.: { name: "name", city: "city" }
182      * @param object
183      * @param <T>
184      * @return The modified object
185      */
186     public static <T> T setStringsInStringProperties(T object) {
187         try {
188             final List<String> stringFields = allStringPropertiesOf(object);
189
190             BeanUtils.populate(object, stringFields.stream()
191                 .collect(toMap(identity(), identity())));
192
193             return object;
194         } catch (Exception e) {
195             throw new RuntimeException(e);
196         }
197     }
198
199     public static void registerCloudConfigurationValueGenerator() {
200         BeanMatchers.registerValueGenerator(() -> new CloudConfiguration(
201                 randomAlphabetic(7), randomAlphabetic(7), randomAlphabetic(7)
202             ), CloudConfiguration.class);
203     }
204
205     public static OngoingStubbing<InputStream> mockGetRawBodyWithStringBody(HttpResponse<String> httpResponse, String body) {
206         try {
207             return when(httpResponse.getRawBody()).thenReturn(IOUtils.toInputStream(body, StandardCharsets.UTF_8.name()));
208         } catch (IOException e) {
209             ExceptionUtils.rethrow(e);
210         }
211         return null; //never shall get here
212     }
213
214     public static HttpResponse<String> createTestHttpResponse(int statusCode, String entity) throws Exception {
215         HttpResponseFactory factory = new DefaultHttpResponseFactory();
216         org.apache.http.HttpResponse response = factory.newHttpResponse(new BasicStatusLine(HTTP_1_1, statusCode, null), null);
217         if (entity != null) {
218             response.setEntity(new StringEntity(entity));
219         }
220         return new HttpResponse<>(response, String.class, null);
221     }
222
223
224     public static class JavaxRsClientMocks {
225         private final javax.ws.rs.client.Client fakeClient;
226         private final javax.ws.rs.client.Invocation.Builder fakeBuilder;
227         private final javax.ws.rs.client.Invocation fakeInvocation;
228         private final Response fakeResponse;
229
230         public javax.ws.rs.client.Client getFakeClient() {
231             return fakeClient;
232         }
233
234         public javax.ws.rs.client.Invocation.Builder getFakeBuilder() {
235             return fakeBuilder;
236         }
237
238         public Response getFakeResponse() {
239             return fakeResponse;
240         }
241
242         public JavaxRsClientMocks() {
243             final MockSettings mockSettings = withSettings().defaultAnswer(new TriesToReturnMockByType());
244
245             fakeClient = mock(javax.ws.rs.client.Client.class, mockSettings);
246             fakeBuilder = mock(javax.ws.rs.client.Invocation.Builder.class, mockSettings);
247             fakeInvocation = mock(javax.ws.rs.client.Invocation.class, mockSettings);
248             fakeResponse = mock(Response.class, mockSettings);
249             final javax.ws.rs.client.WebTarget fakeWebTarget = mock(javax.ws.rs.client.WebTarget.class, mockSettings);
250
251             TriesToReturnMockByType.setAvailableMocks(
252                     fakeClient,
253                     fakeWebTarget,
254                     fakeBuilder,
255                     fakeInvocation,
256                     fakeResponse
257             );
258             Mockito.when(fakeBuilder.get(any(Class.class))).thenReturn(null);
259             Mockito.when(fakeBuilder.get(any(GenericType.class))).thenReturn(null);
260             Mockito.when(fakeResponse.getStatus()).thenReturn(200);
261             Mockito.when(fakeResponse.getStatusInfo()).thenReturn(Response.Status.OK);
262             Mockito.when(fakeResponse.readEntity(Service.class)).thenReturn(null);
263             Mockito.when(fakeResponse.readEntity(InputStream.class)).thenReturn(new ByteArrayInputStream(new byte[]{}));
264             Mockito.when(fakeResponse.readEntity(String.class)).thenReturn(null);
265         }
266     }
267
268     /*
269        inspired out from newer Mockito version
270         returns a mock from given list if it's a matching return-type
271     */
272     private static class TriesToReturnMockByType implements Answer<Object>, Serializable {
273         private final Answer<Object> defaultReturn = RETURNS_DEFAULTS;
274         private static List<Object> availableMocks = ImmutableList.of();
275
276         static void setAvailableMocks(Object... mocks) {
277             availableMocks = ImmutableList.copyOf(mocks);
278         }
279
280         public Object answer(InvocationOnMock invocation) throws Throwable {
281             Class<?> methodReturnType = invocation.getMethod().getReturnType();
282
283             return availableMocks.stream()
284                     .filter(mock -> methodReturnType.isAssignableFrom(mock.getClass()))
285                     //.peek(m -> logger.info("found a mock: " + m.getClass().getName()))
286                     .findFirst()
287                     .orElse(defaultReturn.answer(invocation));
288         }
289     }
290
291
292     //The method mocks only some methods used in my case
293     //You may add some other when for your test here
294     public static Response mockResponseForJavaxClient(Client javaxClientMock) {
295         Response  mockResponse = mock(Response.class);
296         WebTarget webTarget = mock(WebTarget.class);
297         Invocation.Builder builder = mock(Invocation.Builder.class);
298         when(javaxClientMock.target(any(URI.class))).thenReturn(webTarget);
299         when(webTarget.path(any())).thenReturn(webTarget);
300         when(webTarget.request(any(MediaType.class))).thenReturn(builder);
301         when(builder.headers(any())).thenReturn(builder);
302         when(builder.header(any(), any())).thenReturn(builder);
303         when(builder.get()).thenReturn(mockResponse);
304         return mockResponse;
305     }
306
307
308     public interface Test {
309
310         void apply() throws AsdcCatalogException;
311     }
312
313     public static void testWithSystemProperty(String key, String value, Test test) throws Exception {
314         SystemProperties systemProperties = new SystemProperties();
315         //use reflection to invoke protected method
316         Environment originalEnvironment = (Environment) MethodUtils
317             .invokeMethod(systemProperties, true, "getEnvironment");
318
319         try {
320             Environment environment = mock(Environment.class);
321             systemProperties.setEnvironment(environment);
322             when(environment.getRequiredProperty(key)).thenReturn(value);
323             when(environment.containsProperty(key)).thenReturn(true);
324             test.apply();
325         }
326         finally {
327             systemProperties.setEnvironment(originalEnvironment);
328         }
329     }
330
331     private static RandomStringGenerator generator = new RandomStringGenerator.Builder()
332             .withinRange('0', 'z')
333             .filteredBy(LETTERS, DIGITS)
334             .build();
335
336     public static String generateRandomAlphaNumeric(int length) {
337         return generator.generate(length);
338     }
339
340     @DataProvider
341     public static Object[][] trueAndFalse() {
342         return new Object[][]{{true}, {false}};
343     }
344
345 }