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