2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.model.basicmodel.test;
23 import java.io.ByteArrayInputStream;
24 import java.io.ByteArrayOutputStream;
27 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
28 import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
29 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
30 import org.onap.policy.apex.model.basicmodel.dao.ApexDao;
31 import org.onap.policy.apex.model.basicmodel.dao.ApexDaoFactory;
32 import org.onap.policy.apex.model.basicmodel.dao.DaoParameters;
33 import org.onap.policy.apex.model.basicmodel.handling.ApexModelFileWriter;
34 import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
35 import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
36 import org.onap.policy.common.utils.resources.ResourceUtils;
37 import org.slf4j.ext.XLogger;
38 import org.slf4j.ext.XLoggerFactory;
41 * This class tests reading and writing of Apex models to file and to a database using JPA. It also tests validation of
42 * Apex models. This class is designed for use in unit tests in modules that define Apex models.
44 * @author Liam Fallon (liam.fallon@ericsson.com)
45 * @param <M> the generic type
47 public class TestApexModel<M extends AxModel> {
48 private static final String MODEL_IS_INVALID = "model is invalid ";
49 private static final String ERROR_PROCESSING_FILE = "error processing file ";
50 private static final String TEST_MODEL_UNEQUAL_STR = "test model does not equal model read from XML file ";
51 private static final String TEMP_FILE_CREATE_ERR_STR = "error creating temporary file for Apex model";
53 private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestApexModel.class);
55 // The root model class that specifies the root to import and export from
56 private final Class<M> rootModelClass;
58 // The class that provides the model
59 private TestApexModelCreator<M> modelCreator = null;
62 * Constructor, defines the subclass of {@link AxModel} that is being tested and the {@link TestApexModelCreator}
63 * object that is used to generate Apex models.
65 * @param rootModelClass the Apex model class, a sub class of {@link AxModel}
66 * @param modelCreator the @link TestApexModelCreator} that will generate Apex models of various types for testing
68 public TestApexModel(final Class<M> rootModelClass, final TestApexModelCreator<M> modelCreator) {
69 this.rootModelClass = rootModelClass;
70 this.modelCreator = modelCreator;
74 * Get a test Apex model using the model creator.
76 * @return the test Apex model
78 public final M getModel() {
79 return modelCreator.getModel();
83 * Test write and read in XML format.
85 * @throws ApexException on write/read errors
87 public final void testApexModelWriteReadXml() throws ApexException {
88 LOGGER.debug("running testApexModelWriteReadXML . . .");
90 final M model = modelCreator.getModel();
92 // Write the file to disk
96 xmlFile = File.createTempFile("ApexModel", ".xml");
97 xmlFile.deleteOnExit();
98 } catch (final Exception e) {
99 LOGGER.warn(TEMP_FILE_CREATE_ERR_STR, e);
100 throw new ApexException(TEMP_FILE_CREATE_ERR_STR, e);
102 new ApexModelFileWriter<M>(true).apexModelWriteXmlFile(model, rootModelClass, xmlFile.getPath());
104 // Read the file from disk
105 final ApexModelReader<M> modelReader = new ApexModelReader<>(rootModelClass);
108 final URL apexModelUrl = ResourceUtils.getLocalFile(xmlFile.getAbsolutePath());
109 final M fileModel = modelReader.read(apexModelUrl.openStream());
110 checkModelEquality(model, fileModel, TEST_MODEL_UNEQUAL_STR + xmlFile.getAbsolutePath());
111 } catch (final Exception e) {
112 LOGGER.warn(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e);
113 throw new ApexException(ERROR_PROCESSING_FILE + xmlFile.getAbsolutePath(), e);
116 final ApexModelWriter<M> modelWriter = new ApexModelWriter<>(rootModelClass);
117 modelWriter.getCDataFieldSet().add("description");
118 modelWriter.getCDataFieldSet().add("logic");
119 modelWriter.getCDataFieldSet().add("uiLogic");
121 final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
122 modelWriter.write(model, baOutputStream);
123 final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray());
124 final M byteArrayModel = modelReader.read(baInputStream);
126 checkModelEquality(model, byteArrayModel, "test model does not equal XML marshalled and unmarshalled model");
128 LOGGER.debug("ran testApexModelWriteReadXML");
132 * Test write and read in JSON format.
134 * @throws ApexException on write/read errors
136 public final void testApexModelWriteReadJson() throws ApexException {
137 LOGGER.debug("running testApexModelWriteReadJSON . . .");
139 final M model = modelCreator.getModel();
141 // Write the file to disk
144 jsonFile = File.createTempFile("ApexModel", ".xml");
145 jsonFile.deleteOnExit();
146 } catch (final Exception e) {
147 LOGGER.warn(TEMP_FILE_CREATE_ERR_STR, e);
148 throw new ApexException(TEMP_FILE_CREATE_ERR_STR, e);
150 new ApexModelFileWriter<M>(true).apexModelWriteJsonFile(model, rootModelClass, jsonFile.getPath());
152 // Read the file from disk
153 final ApexModelReader<M> modelReader = new ApexModelReader<>(rootModelClass);
156 final URL apexModelUrl = ResourceUtils.getLocalFile(jsonFile.getAbsolutePath());
157 final M fileModel = modelReader.read(apexModelUrl.openStream());
158 checkModelEquality(model, fileModel, TEST_MODEL_UNEQUAL_STR + jsonFile.getAbsolutePath());
159 } catch (final Exception e) {
160 LOGGER.warn(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
161 throw new ApexException(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
164 final ApexModelWriter<M> modelWriter = new ApexModelWriter<>(rootModelClass);
165 modelWriter.setJsonOutput(true);
167 final ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
168 modelWriter.write(model, baOutputStream);
169 final ByteArrayInputStream baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray());
170 final M byteArrayModel = modelReader.read(baInputStream);
172 checkModelEquality(model, byteArrayModel, "test model does not equal JSON marshalled and unmarshalled model");
174 LOGGER.debug("ran testApexModelWriteReadJSON");
178 * Test write and read of an Apex model to database using JPA.
180 * @param daoParameters the DAO parameters to use for JPA/JDBC
181 * @throws ApexException thrown on errors writing or reading the model to database
183 public final void testApexModelWriteReadJpa(final DaoParameters daoParameters) throws ApexException {
184 LOGGER.debug("running testApexModelWriteReadJPA . . .");
186 final M model = modelCreator.getModel();
188 final ApexDao apexDao = new ApexDaoFactory().createApexDao(daoParameters);
189 apexDao.init(daoParameters);
191 apexDao.create(model);
192 final M dbJpaModel = apexDao.get(rootModelClass, model.getKey());
195 checkModelEquality(model, dbJpaModel, "test model does not equal model written and read using generic JPA");
197 LOGGER.debug("ran testApexModelWriteReadJPA");
201 * Test that an Apex model is valid.
203 * @return the result of the validation
204 * @throws ApexException thrown on errors validating the Apex model
206 public final AxValidationResult testApexModelValid() throws ApexException {
207 LOGGER.debug("running testApexModelVaid . . .");
209 final M model = modelCreator.getModel();
210 final AxValidationResult result = model.validate(new AxValidationResult());
212 if (!result.isValid()) {
213 String message = MODEL_IS_INVALID + result.toString();
214 LOGGER.warn(message);
215 throw new ApexException(message);
218 LOGGER.debug("ran testApexModelVaid");
223 * Test that an Apex model is structured incorrectly.
225 * @return the result of the validation
226 * @throws ApexException thrown on errors validating the Apex model
228 public final AxValidationResult testApexModelVaidateMalstructured() throws ApexException {
229 LOGGER.debug("running testApexModelVaidateMalstructured . . .");
231 final M model = modelCreator.getMalstructuredModel();
232 final AxValidationResult result = model.validate(new AxValidationResult());
234 if (result.isValid()) {
235 String message = "model should not be valid " + result.toString();
236 LOGGER.warn(message);
237 throw new ApexException(message);
240 LOGGER.debug("ran testApexModelVaidateMalstructured");
245 * Test that an Apex model has observations.
247 * @return the result of the validation
248 * @throws ApexException thrown on errors validating the Apex model
250 public final AxValidationResult testApexModelVaidateObservation() throws ApexException {
251 LOGGER.debug("running testApexModelVaidateObservation . . .");
253 final M model = modelCreator.getObservationModel();
254 final AxValidationResult result = model.validate(new AxValidationResult());
256 if (!result.isValid()) {
257 String message = MODEL_IS_INVALID + result.toString();
258 LOGGER.warn(message);
259 throw new ApexException(message);
262 if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.OBSERVATION)) {
263 LOGGER.warn("model should have observations");
264 throw new ApexException("model should have observations");
267 LOGGER.debug("ran testApexModelVaidateObservation");
272 * Test that an Apex model has warnings.
274 * @return the result of the validation
275 * @throws ApexException thrown on errors validating the Apex model
277 public final AxValidationResult testApexModelVaidateWarning() throws ApexException {
278 LOGGER.debug("running testApexModelVaidateWarning . . .");
280 final M model = modelCreator.getWarningModel();
281 final AxValidationResult result = model.validate(new AxValidationResult());
283 if (!result.isValid()) {
284 String message = MODEL_IS_INVALID + result.toString();
285 LOGGER.warn(message);
286 throw new ApexException(message);
289 if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.WARNING)) {
290 LOGGER.warn("model should have warnings");
291 throw new ApexException("model should have warnings");
294 LOGGER.debug("ran testApexModelVaidateWarning");
299 * Test that an Apex model is invalid.
301 * @return the result of the validation
302 * @throws ApexException thrown on errors validating the Apex model
304 public final AxValidationResult testApexModelVaidateInvalidModel() throws ApexException {
305 LOGGER.debug("running testApexModelVaidateInvalidModel . . .");
307 final M model = modelCreator.getInvalidModel();
308 final AxValidationResult result = model.validate(new AxValidationResult());
310 if (result.isValid()) {
311 String message = "model should not be valid " + result.toString();
312 LOGGER.warn(message);
313 throw new ApexException(message);
316 LOGGER.debug("ran testApexModelVaidateInvalidModel");
321 * Check if two models are equal.
323 * @param leftModel the left model
324 * @param rightModel the right model
325 * @param errorMessage the error message to output on inequality
326 * @throws ApexException the exception to throw on inequality
328 public void checkModelEquality(final M leftModel, final M rightModel, final String errorMessage)
329 throws ApexException {
330 if (!leftModel.equals(rightModel)) {
331 LOGGER.warn(errorMessage);
332 throw new ApexException(errorMessage);