aboutsummaryrefslogtreecommitdiffstats
path: root/model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/test/TestApexModel.java
blob: 9dde47d05e67ad0a1ec996ef0f287c6e7073363c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2021-2022 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.model.basicmodel.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
import org.onap.policy.apex.model.basicmodel.concepts.AxModel;
import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelFileWriter;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelReader;
import org.onap.policy.apex.model.basicmodel.handling.ApexModelWriter;
import org.onap.policy.common.utils.resources.ResourceUtils;
import org.slf4j.ext.XLogger;
import org.slf4j.ext.XLoggerFactory;

/**
 * This class tests reading and writing of Apex models to file and to a database using JPA. It also tests validation of
 * Apex models. This class is designed for use in unit tests in modules that define Apex models.
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 * @param <M> the generic type
 */
public class TestApexModel<M extends AxModel> {
    private static final String MODEL_IS_INVALID = "model is invalid ";
    private static final String ERROR_PROCESSING_FILE = "error processing file ";
    private static final String TEST_MODEL_UNEQUAL_STR = "test model does not equal model read from file ";
    private static final String TEMP_FILE_CREATE_ERR_STR = "error creating temporary file for Apex model";

    private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestApexModel.class);

    // The root model class that specifies the root to import and export from
    private final Class<M> rootModelClass;

    // The class that provides the model
    private TestApexModelCreator<M> modelCreator = null;

    /**
     * Constructor, defines the subclass of {@link AxModel} that is being tested and the {@link TestApexModelCreator}
     * object that is used to generate Apex models.
     *
     * @param rootModelClass the Apex model class, a sub class of {@link AxModel}
     * @param modelCreator the @link TestApexModelCreator} that will generate Apex models of various types for testing
     */
    public TestApexModel(final Class<M> rootModelClass, final TestApexModelCreator<M> modelCreator) {
        this.rootModelClass = rootModelClass;
        this.modelCreator = modelCreator;
    }

    /**
     * Get a test Apex model using the model creator.
     *
     * @return the test Apex model
     */
    public final M getModel() {
        return modelCreator.getModel();
    }

    /**
     * Test write and read in JSON format.
     *
     * @throws ApexException on write/read errors
     */
    public final void testApexModelWriteReadJson() throws ApexException {
        LOGGER.debug("running testApexModelWriteReadJSON . . .");

        final var model = modelCreator.getModel();

        // Write the file to disk
        File jsonFile;
        try {
            jsonFile = File.createTempFile("ApexModel", ".json");
            jsonFile.deleteOnExit();
        } catch (final Exception e) {
            LOGGER.warn(TEMP_FILE_CREATE_ERR_STR, e);
            throw new ApexException(TEMP_FILE_CREATE_ERR_STR, e);
        }
        new ApexModelFileWriter<M>(true).apexModelWriteJsonFile(model, rootModelClass, jsonFile.getPath());

        // Read the file from disk
        final ApexModelReader<M> modelReader = new ApexModelReader<>(rootModelClass);

        try {
            final var apexModelUrl = ResourceUtils.getLocalFile(jsonFile.getAbsolutePath());
            final var fileModel = modelReader.read(apexModelUrl.openStream());
            checkModelEquality(model, fileModel, TEST_MODEL_UNEQUAL_STR + jsonFile.getAbsolutePath());
        } catch (final Exception e) {
            LOGGER.warn(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
            throw new ApexException(ERROR_PROCESSING_FILE + jsonFile.getAbsolutePath(), e);
        }

        final ApexModelWriter<M> modelWriter = new ApexModelWriter<>(rootModelClass);

        final var baOutputStream = new ByteArrayOutputStream();
        modelWriter.write(model, baOutputStream);
        final var baInputStream = new ByteArrayInputStream(baOutputStream.toByteArray());
        final var byteArrayModel = modelReader.read(baInputStream);

        checkModelEquality(model, byteArrayModel, "test model does not equal JSON marshalled and unmarshalled model");

        LOGGER.debug("ran testApexModelWriteReadJSON");
    }

    /**
     * Test that an Apex model is valid.
     *
     * @return the result of the validation
     * @throws ApexException thrown on errors validating the Apex model
     */
    public final AxValidationResult testApexModelValid() throws ApexException {
        LOGGER.debug("running testApexModelVaid . . .");

        final var model = modelCreator.getModel();
        final AxValidationResult result = model.validate(new AxValidationResult());

        if (!result.isValid()) {
            String message = MODEL_IS_INVALID + result.toString();
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        LOGGER.debug("ran testApexModelVaid");
        return result;
    }

    /**
     * Test that an Apex model is structured incorrectly.
     *
     * @return the result of the validation
     * @throws ApexException thrown on errors validating the Apex model
     */
    public final AxValidationResult testApexModelVaidateMalstructured() throws ApexException {
        LOGGER.debug("running testApexModelVaidateMalstructured . . .");

        final var model = modelCreator.getMalstructuredModel();
        final AxValidationResult result = model.validate(new AxValidationResult());

        if (result.isValid()) {
            String message = "model should not be valid " + result.toString();
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        LOGGER.debug("ran testApexModelVaidateMalstructured");
        return result;
    }

    /**
     * Test that an Apex model has observations.
     *
     * @return the result of the validation
     * @throws ApexException thrown on errors validating the Apex model
     */
    public final AxValidationResult testApexModelVaidateObservation() throws ApexException {
        LOGGER.debug("running testApexModelVaidateObservation . . .");

        final var model = modelCreator.getObservationModel();
        final AxValidationResult result = model.validate(new AxValidationResult());

        if (!result.isValid()) {
            String message = MODEL_IS_INVALID + result.toString();
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.OBSERVATION)) {
            LOGGER.warn("model should have observations");
            throw new ApexException("model should have observations");
        }

        LOGGER.debug("ran testApexModelVaidateObservation");
        return result;
    }

    /**
     * Test that an Apex model has warnings.
     *
     * @return the result of the validation
     * @throws ApexException thrown on errors validating the Apex model
     */
    public final AxValidationResult testApexModelVaidateWarning() throws ApexException {
        LOGGER.debug("running testApexModelVaidateWarning . . .");

        final var model = modelCreator.getWarningModel();
        final AxValidationResult result = model.validate(new AxValidationResult());

        if (!result.isValid()) {
            String message = MODEL_IS_INVALID + result.toString();
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        if (!result.getValidationResult().equals(AxValidationResult.ValidationResult.WARNING)) {
            LOGGER.warn("model should have warnings");
            throw new ApexException("model should have warnings");
        }

        LOGGER.debug("ran testApexModelVaidateWarning");
        return result;
    }

    /**
     * Test that an Apex model is invalid.
     *
     * @return the result of the validation
     * @throws ApexException thrown on errors validating the Apex model
     */
    public final AxValidationResult testApexModelVaidateInvalidModel() throws ApexException {
        LOGGER.debug("running testApexModelVaidateInvalidModel . . .");

        final var model = modelCreator.getInvalidModel();
        final AxValidationResult result = model.validate(new AxValidationResult());

        if (result.isValid()) {
            String message = "model should not be valid " + result.toString();
            LOGGER.warn(message);
            throw new ApexException(message);
        }

        LOGGER.debug("ran testApexModelVaidateInvalidModel");
        return result;
    }

    /**
     * Check if two models are equal.
     *
     * @param leftModel the left model
     * @param rightModel the right model
     * @param errorMessage the error message to output on inequality
     * @throws ApexException the exception to throw on inequality
     */
    public void checkModelEquality(final M leftModel, final M rightModel, final String errorMessage)
        throws ApexException {
        if (!leftModel.equals(rightModel)) {
            LOGGER.warn(errorMessage);
            throw new ApexException(errorMessage);
        }
    }
}