2 * ===============================LICENSE_START======================================
4 * ================================================================================
5 * Copyright © 2017 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.dcae.apod.analytics.test;
23 import org.json.JSONException;
24 import org.junit.Assert;
25 import org.skyscreamer.jsonassert.JSONAssert;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
29 import java.io.BufferedReader;
31 import java.io.FileOutputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.InputStreamReader;
35 import java.io.ObjectOutputStream;
36 import java.io.OutputStreamWriter;
37 import java.lang.reflect.Field;
39 import java.net.URLClassLoader;
40 import java.nio.charset.Charset;
41 import java.nio.file.Paths;
42 import java.security.AccessController;
43 import java.security.PrivilegedAction;
44 import java.util.Arrays;
46 import static java.nio.file.Files.deleteIfExists;
47 import static java.nio.file.Files.exists;
50 * Base common test class for all DCAE Analytics Test e.g. unit tests, integration test, CDAP tests etc.
52 * @author Rajiv Singla . Creation Date: 10/19/2016.
54 abstract class BaseDCAEAnalyticsCommonTest {
56 protected static final Logger LOG = LoggerFactory.getLogger(BaseDCAEAnalyticsCommonTest.class);
59 * Asserts if expected Json String and actual Json String contain the same properties ignoring
60 * property order. Simple String assertion might fail as property order during serialization and deserialization
61 * is generally non-deterministic. Also proper error message are generated more missing or unexpected
64 * @param expectedJsonString expected Json String
65 * @param actualJsonString actual Json String
66 * @throws JSONException Json Exception
68 public static void assertJson(String expectedJsonString, String actualJsonString) throws JSONException {
69 JSONAssert.assertEquals(expectedJsonString, actualJsonString, true);
73 * Converts given file location to String
75 * @param fileLocation location of the file which needs to be converted to String
76 * @return Contents of file as string
77 * @throws IOException IOException
79 public static String fromStream(String fileLocation) throws IOException {
80 final InputStream jsonFileInputStream =
81 BaseDCAEAnalyticsCommonTest.class.getClassLoader().getResourceAsStream(fileLocation);
82 Assert.assertNotNull("Json File Location must be valid", jsonFileInputStream);
83 try (BufferedReader reader =
84 new BufferedReader(new InputStreamReader(jsonFileInputStream, Charset.forName("UTF-8")))) {
85 final StringBuilder result = new StringBuilder();
86 final String newLine = System.getProperty("line.separator");
87 String line = reader.readLine();
88 while (line != null) {
91 line = reader.readLine();
93 jsonFileInputStream.close();
94 return result.toString();
100 * Checks if object can be serialized properly
102 * @param object input object
103 * @param callingClass calling class
104 * @throws IOException IOException
106 public static void testSerialization(Object object, Class<?> callingClass) throws IOException {
107 final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();
108 final File serializedOutputFile =
109 new File(location.getPath() + String.format("serialization/%s.ser", object.getClass().getSimpleName()));
111 // Maybe file already try deleting it first
112 final boolean deleteIfExists = deleteIfExists(Paths.get(serializedOutputFile.getPath()));
114 if (deleteIfExists) {
115 LOG.warn("Previous serialization file was overwritten at location: {}", serializedOutputFile.getPath());
118 boolean mkdirs = true;
119 if (!exists(Paths.get(serializedOutputFile.getParentFile().getPath()))) {
120 mkdirs = serializedOutputFile.getParentFile().mkdirs();
123 try (FileOutputStream fileOutputStream = new FileOutputStream(serializedOutputFile);
124 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
125 objectOutputStream.writeObject(object);
126 LOG.debug("Successfully created serialization file at location: {}", serializedOutputFile.getPath());
129 throw new IllegalStateException(
130 String.format("Failed to create location to store serialization file: %s",
131 serializedOutputFile));
136 * Writes Text to Output file
138 * @param textFileLocation - location of text file e.g. textfiles/fileName.json
139 * @param content - file content
140 * @param callingClass - calling class
141 * @throws IOException - ioException
143 public static void writeToOutputTextFile(String textFileLocation, String content, Class<?> callingClass) throws
145 final URL location = callingClass.getProtectionDomain().getCodeSource().getLocation();
146 final File fileLocation = new File(location.getPath() + textFileLocation);
148 // Maybe file already try deleting it first
149 final boolean deleteIfExists = deleteIfExists(Paths.get(fileLocation.getPath()));
151 if (deleteIfExists) {
152 LOG.warn("Previous file will be overwritten at location: {}", fileLocation.getPath());
155 boolean mkdirs = true;
156 if (!exists(Paths.get(fileLocation.getParentFile().getPath()))) {
157 mkdirs = fileLocation.getParentFile().mkdirs();
161 FileOutputStream fileOutputStream = new FileOutputStream(fileLocation);
162 OutputStreamWriter outputStream =
163 new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8"))) {
164 outputStream.write(content);
165 LOG.debug("Successfully created text file at location: {}", fileLocation.getPath());
168 throw new IllegalStateException(
169 String.format("Failed to create location to store text file: %s", fileLocation));
176 * For testing purposes only we may sometime we may want to access private fields of underlying
177 * object to confirm the values are setup correctly.
179 * This method uses java reflection to get the value to private object in the class
181 * @param object Actual object which has the private field you want to check
182 * @param fieldName Field name in the Actual Object you want to get the value of
183 * @param privateFieldClass Type of the private field
184 * @param <T> Class of Actual Object
185 * @param <U> Class of private field
186 * @return value of the private field
188 public static <T, U> U getPrivateFiledValue(T object, String fieldName, Class<U> privateFieldClass) {
190 final Class<?> objectClass = object.getClass();
192 final Field privateField = objectClass.getDeclaredField(fieldName);
195 // mark private field to be accessible for testing purposes
196 AccessController.doPrivileged(new PrivilegedAction() {
198 public Object run() {
199 privateField.setAccessible(true);
205 return privateFieldClass.cast(privateField.get(object));
207 } catch (IllegalAccessException e) {
208 LOG.error("Unable to access field: {}", fieldName);
209 throw new IllegalStateException(e);
211 } catch (NoSuchFieldException e) {
212 LOG.error("Unable to locate field name: {} in class: {}", fieldName, objectClass.getSimpleName());
213 throw new IllegalStateException(e);
221 * Prints classpath jars which are visible inside the class
223 * @param classLoader classloader of the calling class
225 public static void dumpClasspath(ClassLoader classLoader) {
227 LOG.info("Dumping ClassPath for classloader: {}", classLoader);
229 if (classLoader instanceof URLClassLoader) {
231 URLClassLoader ucl = (URLClassLoader) classLoader;
232 LOG.info("\t ==========>>>" + Arrays.toString(ucl.getURLs()));
235 LOG.info("\t(cannot display components as not a URLClassLoader)");
238 if (classLoader.getParent() != null) {
239 dumpClasspath(classLoader.getParent());