Add sdc startup in IT
[sdc.git] / integration-tests / src / test / java / org / onap / sdc / backend / ci / tests / api / ComponentBaseTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 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.onap.sdc.backend.ci.tests.api;
22
23 import ch.qos.logback.classic.Level;
24 import ch.qos.logback.classic.LoggerContext;
25 import com.aventstack.extentreports.ExtentTest;
26 import com.aventstack.extentreports.Status;
27 import java.io.File;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Objects;
34 import java.util.stream.Collectors;
35 import org.apache.commons.collections.CollectionUtils;
36 import org.apache.logging.log4j.LogManager;
37 import org.apache.logging.log4j.Logger;
38 import org.onap.sdc.backend.ci.tests.config.Config;
39 import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails;
40 import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum;
41 import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse;
42 import org.onap.sdc.backend.ci.tests.utils.Utils;
43 import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils;
44 import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory;
45 import org.onap.sdc.backend.ci.tests.utils.general.FileHandling;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
48 import org.openecomp.sdc.be.model.Component;
49 import org.openecomp.sdc.be.model.Product;
50 import org.openecomp.sdc.be.model.Resource;
51 import org.openecomp.sdc.be.model.Service;
52 import org.openecomp.sdc.be.model.User;
53 import org.onap.sdc.backend.ci.tests.utils.rest.BaseRestUtils;
54 import org.onap.sdc.backend.ci.tests.utils.rest.CatalogRestUtils;
55 import org.onap.sdc.backend.ci.tests.utils.rest.ProductRestUtils;
56 import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils;
57 import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser;
58 import org.onap.sdc.backend.ci.tests.utils.rest.ServiceRestUtils;
59 import org.slf4j.LoggerFactory;
60 import org.testng.ITestContext;
61 import org.testng.ITestResult;
62 import org.testng.annotations.AfterMethod;
63 import org.testng.annotations.AfterSuite;
64 import org.testng.annotations.BeforeMethod;
65 import org.testng.annotations.BeforeSuite;
66
67 public abstract class ComponentBaseTest {
68
69     protected static Logger logger = LogManager.getLogger(ComponentBaseTest.class);
70
71     protected static final String REPORT_FOLDER = "target" + File.separator + "ExtentReport" + File.separator;
72     private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
73     public static Config config;
74     protected static ITestContext myContext;
75
76
77     /**************** METHODS ****************/
78     public static ExtentTest getExtendTest() {
79         SomeInterface testManager = new ExtentTestManager();
80         return testManager.getTest();
81     }
82
83     public enum ComponentOperationEnum {
84         CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
85     }
86
87     public ComponentBaseTest() {
88         LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
89         lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
90         lc.getLogger("com.datastax").setLevel(Level.INFO);
91         lc.getLogger("io.netty").setLevel(Level.INFO);
92         lc.getLogger("c.d").setLevel(Level.INFO);
93     }
94
95     public static String getReportFolder() {
96         return REPORT_FOLDER;
97     }
98
99     @BeforeSuite(alwaysRun = true)
100     public void setupBeforeSuite(ITestContext context) throws Exception {
101         config = Utils.getConfig();
102         myContext = context;
103         ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
104         AtomicOperationUtils.createDefaultConsumer(true);
105         performClean();
106     }
107
108     @BeforeMethod(alwaysRun = true)
109     public void setupBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
110         if (!"onboardVNFShotFlow".equals(method.getName()) &&
111             !"onboardPNFFlow".equals(method.getName()) ) {
112             logger.info("ExtentReport instance started from BeforeMethod...");
113             ExtentTestManager.startTest(method.getName());
114             ExtentTestManager.assignCategory(this.getClass());
115
116         } else {
117             logger.debug("ExtentReport instance started from Test...");
118         }
119     }
120
121     @AfterMethod(alwaysRun = true)
122     public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
123         int status = result.getStatus();
124         switch (status) {
125             case ITestResult.SUCCESS:
126                 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
127                 break;
128
129             case ITestResult.FAILURE:
130                 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
131                 getExtendTest().log(Status.ERROR, result.getThrowable());
132                 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
133                 break;
134
135             case ITestResult.SKIP:
136                 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
137                 break;
138             default:
139                 break;
140         }
141         ExtentTestManager.endTest();
142     }
143
144     @AfterSuite(alwaysRun = true)
145     public static void shutdownJanusGraph() throws Exception {
146         performClean();
147     }
148
149     public void setLog(String fromDataProvider) {
150         ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
151         ExtentTestManager.assignCategory(this.getClass());
152     }
153
154     protected static void performClean() throws Exception {
155         if (!config.getSystemUnderDebug()) {
156             deleteCreatedComponents(getCatalogAsMap());
157             FileHandling.overWriteExistindDir("target/outputCsar");
158         } else {
159             System.out.println("Accordindig to configuration components will not be deleted, in case to unable option to delete, please change systemUnderDebug parameter value to false ...");
160         }
161     }
162
163     private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
164         final String userId = UserRoleEnum.DESIGNER.getUserId();
165
166         List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
167         if (!CollectionUtils.isEmpty(resourcesArrayList)) {
168             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
169             for (String uId : collect) {
170                 ResourceRestUtils.markResourceToDelete(uId, userId);
171             }
172             ResourceRestUtils.deleteMarkedResources(userId);
173         }
174
175         resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
176         if (resourcesArrayList.size() > 0) {
177             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
178             for (String uId : collect) {
179                 ServiceRestUtils.markServiceToDelete(uId, userId);
180             }
181             ServiceRestUtils.deleteMarkedServices(userId);
182         }
183     }
184
185     protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
186
187
188         List<String> genericCollection = new ArrayList<>();
189         if(resourcesArrayList.get(0) != null) {
190             ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
191             resourcesArrayList.stream().filter(Objects::nonNull).
192                     filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).
193                     filter(f -> f.getUniqueId() != null).
194                     map(Component::getUniqueId).
195                     collect(Collectors.toList()).
196                     forEach((i) -> buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i));
197         }
198         return genericCollection;
199     }
200
201     public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
202                                                           List<String> genericCollection, String i) {
203         try {
204             switch (componentTypeEnum) {
205                 case RESOURCE:
206                     RestResponse resource = ResourceRestUtils.getResource(i);
207                     Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
208                     Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
209                     Collection<String> values = allVersions.values();
210                     genericCollection.addAll(values);
211
212                     break;
213                 case SERVICE:
214                     RestResponse service = ServiceRestUtils.getService(i);
215                     Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
216                     allVersions = convertServiceResponseToJavaObject.getAllVersions();
217                     values = allVersions.values();
218                     genericCollection.addAll(values);
219
220                     break;
221
222
223                 case PRODUCT:
224                     RestResponse product = ProductRestUtils.getProduct(i);
225                     Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
226                     allVersions = convertProductResponseToJavaObject.getAllVersions();
227                     values = allVersions.values();
228                     genericCollection.addAll(values);
229
230                     break;
231             }
232         } catch (Exception e1) {
233             e1.printStackTrace();
234         }
235     }
236
237     protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
238         RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
239         return ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
240     }
241
242     protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
243         // create new resource from Csar
244         ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
245
246         resourceDetails.setCsarUUID(csarId);
247         resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
248         RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
249         BaseRestUtils.checkCreateResponse(createResource);
250         return ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
251     }
252
253
254 }