Add end-to-end junits for PAP REST API
[policy/pap.git] / main / src / test / java / org / onap / policy / pap / main / rest / e2e / End2EndBase.java
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP PAP
4  * ================================================================================
5  * Copyright (C) 2019 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.onap.policy.pap.main.rest.e2e;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import org.junit.After;
28 import org.junit.AfterClass;
29 import org.junit.BeforeClass;
30 import org.onap.policy.common.parameters.ValidationResult;
31 import org.onap.policy.common.utils.coder.Coder;
32 import org.onap.policy.common.utils.coder.CoderException;
33 import org.onap.policy.common.utils.coder.StandardCoder;
34 import org.onap.policy.common.utils.resources.ResourceUtils;
35 import org.onap.policy.common.utils.services.Registry;
36 import org.onap.policy.models.base.PfModelException;
37 import org.onap.policy.models.pdp.concepts.PdpGroups;
38 import org.onap.policy.models.provider.PolicyModelsProvider;
39 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
40 import org.onap.policy.pap.main.PapConstants;
41 import org.onap.policy.pap.main.PolicyModelsProviderFactoryWrapper;
42 import org.onap.policy.pap.main.PolicyPapRuntimeException;
43 import org.onap.policy.pap.main.rest.CommonPapRestServer;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.yaml.snakeyaml.Yaml;
47
48 public class End2EndBase extends CommonPapRestServer {
49     private static final Logger logger = LoggerFactory.getLogger(End2EndBase.class);
50
51     private static final Coder coder = new StandardCoder();
52     private static final Yaml yaml = new Yaml();
53
54     /**
55      * DB connection. This is kept open until {@link #stop()} is invoked so that the
56      * in-memory DB is not destroyed.
57      */
58     private static PolicyModelsProvider dbConn;
59
60     /**
61      * DAO provider factory.
62      */
63     private static PolicyModelsProviderFactoryWrapper daoFactory;
64
65     /**
66      * Context - should be initialized by setUp() method.
67      */
68     protected End2EndContext context = null;
69
70
71     /**
72      * Starts Main and connects to the DB.
73      *
74      * @throws Exception if an error occurs
75      */
76     @BeforeClass
77     public static void setUpBeforeClass() throws Exception {
78         CommonPapRestServer.setUpBeforeClass();
79
80         daoFactory = Registry.get(PapConstants.REG_PAP_DAO_FACTORY, PolicyModelsProviderFactoryWrapper.class);
81
82         try {
83             dbConn = daoFactory.create();
84         } catch (PfModelException e) {
85             throw new PolicyPapRuntimeException("cannot connect to DB", e);
86         }
87     }
88
89     /**
90      * Tears down.
91      */
92     @AfterClass
93     public static void tearDownAfterClass() {
94         try {
95             dbConn.close();
96         } catch (PfModelException e) {
97             logger.warn("failed to close the DB", e);
98         }
99
100         try {
101             daoFactory.close();
102         } catch (Exception e) {
103             logger.warn("failed to close DAO factory", e);
104         }
105
106         CommonPapRestServer.teardownAfterClass();
107     }
108
109     /**
110      * Tears down.
111      */
112     @After
113     public void tearDown() {
114         if (context != null) {
115             try {
116                 context.stop();
117             } catch (Exception e) {
118                 logger.warn("failed to stop end-to-end context", e);
119             }
120             context = null;
121         }
122
123         super.tearDown();
124     }
125
126     /**
127      * Adds Tosca Policy Types to the DB.
128      *
129      * @param yamlFile name of the YAML file specifying the data to be loaded
130      * @throws PfModelException if a DAO error occurs
131      */
132     public static void addToscaPolicyTypes(String yamlFile) throws PfModelException {
133         ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
134         dbConn.createPolicyTypes(serviceTemplate);
135     }
136
137     /**
138      * Adds Tosca Policies to the DB.
139      *
140      * @param yamlFile name of the YAML file specifying the data to be loaded
141      * @throws PfModelException if a DAO error occurs
142      */
143     public static void addToscaPolicies(String yamlFile) throws PfModelException {
144         ToscaServiceTemplate serviceTemplate = loadYamlFile(yamlFile, ToscaServiceTemplate.class);
145         dbConn.createPolicies(serviceTemplate);
146     }
147
148     /**
149      * Adds PDP groups to the DB.
150      *
151      * @param jsonFile name of the JSON file specifying the data to be loaded
152      * @throws PfModelException if a DAO error occurs
153      */
154     public static void addGroups(String jsonFile) throws PfModelException {
155         PdpGroups groups = loadJsonFile(jsonFile, PdpGroups.class);
156
157         ValidationResult result = groups.validatePapRest();
158         if (!result.isValid()) {
159             throw new PolicyPapRuntimeException("cannot init DB groups from " + jsonFile + ":\n" + result.getResult());
160         }
161
162         dbConn.createPdpGroups(groups.getGroups());
163     }
164
165     /**
166      * Loads an object from a YAML file.
167      *
168      * @param fileName name of the file from which to load
169      * @param clazz the class of the object to be loaded
170      * @return the object that was loaded from the file
171      */
172     protected static <T> T loadYamlFile(String fileName, Class<T> clazz) {
173         File propFile = new File(ResourceUtils.getFilePath4Resource("e2e/" + fileName));
174
175         try (FileInputStream input = new FileInputStream(propFile)) {
176             Object yamlObject = yaml.load(input);
177             String json = coder.encode(yamlObject);
178             T result = coder.decode(json, clazz);
179
180             if (result == null) {
181                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
182             }
183
184             return result;
185
186         } catch (FileNotFoundException e) {
187             throw new PolicyPapRuntimeException("cannot find " + fileName, e);
188
189         } catch (IOException | CoderException e) {
190             throw new PolicyPapRuntimeException("cannot decode " + fileName, e);
191         }
192     }
193
194     /**
195      * Loads an object from a JSON file.
196      *
197      * @param fileName name of the file from which to load
198      * @param clazz the class of the object to be loaded
199      * @return the object that was loaded from the file
200      */
201     protected static <T> T loadJsonFile(String fileName, Class<T> clazz) {
202         String fileName2 = (fileName.startsWith("src/") ? fileName : "e2e/" + fileName);
203         File propFile = new File(ResourceUtils.getFilePath4Resource(fileName2));
204         try {
205             T result = coder.decode(propFile, clazz);
206
207             if (result == null) {
208                 throw new PolicyPapRuntimeException("cannot decode " + clazz.getSimpleName() + " from " + fileName);
209             }
210
211             return result;
212
213         } catch (CoderException e) {
214             throw new RuntimeException(e);
215         }
216     }
217 }