df69c8c17a18ec5d5bbddcdd99a6cb4f5866820f
[dcaegen2/analytics/tca.git] / dcae-analytics-model / src / test / java / org / openecomp / dcae / apod / analytics / model / BaseAnalyticsModelUnitTest.java
1 /*
2  * ===============================LICENSE_START======================================
3  *  dcae-analytics
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
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.openecomp.dcae.apod.analytics.model;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import com.google.common.base.Suppliers;
26 import org.json.JSONException;
27 import org.junit.Assert;
28 import org.junit.BeforeClass;
29 import org.openecomp.dcae.apod.analytics.model.util.json.AnalyticsModelObjectMapperSupplier;
30 import org.openecomp.dcae.apod.analytics.test.BaseDCAEAnalyticsUnitTest;
31
32 import java.io.IOException;
33 import java.io.InputStream;
34
35 import static org.hamcrest.CoreMatchers.is;
36 import static org.junit.Assert.assertThat;
37
38 /**
39  * @author Rajiv Singla . Creation Date: 10/17/2016.
40  */
41 public abstract class BaseAnalyticsModelUnitTest extends BaseDCAEAnalyticsUnitTest {
42
43
44     protected static ObjectMapper objectMapper;
45
46     @BeforeClass
47     public static void beforeClass() {
48         final AnalyticsModelObjectMapperSupplier analyticsModelObjectMapperSupplier =
49                 new AnalyticsModelObjectMapperSupplier();
50         objectMapper = Suppliers.memoize(analyticsModelObjectMapperSupplier).get();
51     }
52
53
54     /**
55      * Deserialize given Json file location to given model class and returns it back without any validation check
56      *
57      * @param jsonFileLocation Classpath location of the json file
58      * @param modelClass       Model Class type
59      * @param <T>              Json Model Type
60      * @return                  Deserialized Model Object
61      */
62     public static <T> T deserializeJsonFileToModel(String jsonFileLocation, Class<T> modelClass) {
63         final InputStream jsonFileInputStream =
64                 BaseDCAEAnalyticsUnitTest.class.getClassLoader().getResourceAsStream(jsonFileLocation);
65         Assert.assertNotNull("Json File Location must be valid", jsonFileInputStream);
66         try {
67             return objectMapper.readValue(jsonFileInputStream, modelClass);
68         } catch (IOException ex) {
69             LOG.error("Error while doing assert Json for fileLocation: {}, modelClass: {}, Exception {}",
70                     jsonFileLocation, modelClass, ex);
71             throw new RuntimeException(ex);
72         } finally {
73             try {
74                 jsonFileInputStream.close();
75             } catch (IOException e) {
76                 LOG.error("Error while closing input stream at file location: {}", jsonFileLocation);
77                 throw new RuntimeException(e);
78             }
79         }
80     }
81
82     /**
83      * Deserialize given Json file location to given model class and then validates deserialization by comparing it
84      * with given expected Object
85      *
86      * @param jsonFileLocation   Classpath location of the json file
87      * @param modelClass         Model Class type
88      * @param expectedJsonObject Expected Json Object
89      * @param <T>                Json Model Type
90      * @return deserialized actual value if expected Json Object matches deserialized object
91      */
92     public static <T> T assertJsonDeserialization(String jsonFileLocation, Class<T> modelClass, T expectedJsonObject) {
93         final T actualValue = deserializeJsonFileToModel(jsonFileLocation, modelClass);
94         assertThat(actualValue, is(expectedJsonObject));
95         return actualValue;
96     }
97
98     public static String serializeModelToJson(Object model) throws JsonProcessingException {
99         return objectMapper.writeValueAsString(model);
100     }
101
102     /**
103      * Converts given model to json string and compare it with json present at given file location
104      *
105      * @param model                    Model which needs to be compared
106      * @param expectedJsonFileLocation Location of file containing expected json string
107      *
108      * @return If assertion passes returns the input model
109      */
110     public static <T> T assertJsonSerialization(T model, String expectedJsonFileLocation) {
111         try {
112             final String actualModelString = serializeModelToJson(model);
113             final String expectedModelString = fromStream(expectedJsonFileLocation);
114             assertJson(expectedModelString, actualModelString);
115             return model;
116         } catch (IOException | JSONException ex) {
117             LOG.error("Error while doing assert Json serialization Assertion: model: {}, " +
118                     "expected Json File Location: {}, Exception {}", model, expectedJsonFileLocation, ex);
119             throw new RuntimeException(ex);
120         }
121
122     }
123
124
125     /**
126      * Checks both serialization and deserialization.
127      *
128      * First checks deserialization and then serialize the deserialized object back to json
129      * and check if matches the given json file location string
130      *
131      * @param jsonFileLocation   Classpath location of the json file
132      * @param modelClass         Class type
133      * @param <T>                Json Model Type
134      *
135      * @return If assertion passes, returns deserialized object
136      */
137
138     public static <T> T assertJsonConversions(String jsonFileLocation, Class<T> modelClass) {
139         //first check deserialization
140         final T actualValue = deserializeJsonFileToModel(jsonFileLocation, modelClass);
141         //then check serialization
142         assertJsonSerialization(actualValue, jsonFileLocation);
143
144         return actualValue;
145     }
146
147
148 }