Remove vulnerable dependency
[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.onap.sdc.backend.ci.tests.config.Config;
37 import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails;
38 import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum;
39 import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse;
40 import org.onap.sdc.backend.ci.tests.utils.Utils;
41 import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils;
42 import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory;
43 import org.onap.sdc.backend.ci.tests.utils.general.FileHandling;
44 import org.onap.sdc.backend.ci.tests.utils.rest.BaseRestUtils;
45 import org.onap.sdc.backend.ci.tests.utils.rest.CatalogRestUtils;
46 import org.onap.sdc.backend.ci.tests.utils.rest.ProductRestUtils;
47 import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils;
48 import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser;
49 import org.onap.sdc.backend.ci.tests.utils.rest.ServiceRestUtils;
50 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
51 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
52 import org.openecomp.sdc.be.model.Component;
53 import org.openecomp.sdc.be.model.Product;
54 import org.openecomp.sdc.be.model.Resource;
55 import org.openecomp.sdc.be.model.Service;
56 import org.openecomp.sdc.be.model.User;
57 import org.openecomp.sdc.logging.api.Logger;
58 import org.openecomp.sdc.logging.api.LoggerFactory;
59 import org.testng.ITestContext;
60 import org.testng.ITestResult;
61 import org.testng.annotations.AfterMethod;
62 import org.testng.annotations.AfterSuite;
63 import org.testng.annotations.BeforeMethod;
64 import org.testng.annotations.BeforeSuite;
65
66 public abstract class ComponentBaseTest {
67
68     protected static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class);
69
70     protected static final String REPORT_FOLDER = "target" + File.separator + "ExtentReport" + File.separator + "API" + File.separator;
71     private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
72     public static Config config;
73     protected static ITestContext myContext;
74
75
76     /**************** METHODS ****************/
77     public static ExtentTest getExtendTest() {
78         SomeInterface testManager = new ExtentTestManager();
79         return testManager.getTest();
80     }
81
82     public enum ComponentOperationEnum {
83         CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
84     }
85
86     public ComponentBaseTest() {
87         LoggerContext lc = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();
88         lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
89         lc.getLogger("com.datastax").setLevel(Level.INFO);
90         lc.getLogger("io.netty").setLevel(Level.INFO);
91         lc.getLogger("c.d").setLevel(Level.INFO);
92     }
93
94     public static String getReportFolder() {
95         return REPORT_FOLDER;
96     }
97
98     @BeforeSuite(alwaysRun = true)
99     public void setupBeforeSuite(ITestContext context) throws Exception {
100         config = Utils.getConfig();
101         myContext = context;
102         ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
103         AtomicOperationUtils.createDefaultConsumer(true);
104         performClean();
105     }
106
107     @BeforeMethod(alwaysRun = true)
108     public void setupBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
109         if (!"onboardVNFShotFlow".equals(method.getName()) &&
110             !"onboardPNFFlow".equals(method.getName())) {
111             logger.info("ExtentReport instance started from BeforeMethod...");
112             ExtentTestManager.startTest(method.getName());
113             ExtentTestManager.assignCategory(this.getClass());
114
115         } else {
116             logger.debug("ExtentReport instance started from Test...");
117         }
118     }
119
120     @AfterMethod(alwaysRun = true)
121     public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
122         int status = result.getStatus();
123         switch (status) {
124             case ITestResult.SUCCESS:
125                 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
126                 break;
127
128             case ITestResult.FAILURE:
129                 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
130                 getExtendTest().log(Status.ERROR, result.getThrowable());
131                 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
132                 break;
133
134             case ITestResult.SKIP:
135                 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
136                 break;
137             default:
138                 break;
139         }
140         ExtentTestManager.endTest();
141     }
142
143     @AfterSuite(alwaysRun = true)
144     public static void shutdownJanusGraph() throws Exception {
145         performClean();
146     }
147
148     public void setLog(String fromDataProvider) {
149         ExtentTestManager
150             .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.isSystemUnderDebug()) {
156             deleteCreatedComponents(getCatalogAsMap());
157             FileHandling.overWriteExistindDir("target/outputCsar");
158         } else {
159             System.out.println(
160                 "Accordindig to configuration components will not be deleted, in case to unable option to delete, please change systemUnderDebug parameter value to false ...");
161         }
162     }
163
164     private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
165         final String userId = UserRoleEnum.DESIGNER.getUserId();
166
167         List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
168         if (!CollectionUtils.isEmpty(resourcesArrayList)) {
169             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
170             for (String uId : collect) {
171                 ResourceRestUtils.markResourceToDelete(uId, userId);
172             }
173             ResourceRestUtils.deleteMarkedResources(userId);
174         }
175
176         resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
177         if (resourcesArrayList.size() > 0) {
178             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
179             for (String uId : collect) {
180                 ServiceRestUtils.markServiceToDelete(uId, userId);
181             }
182             ServiceRestUtils.deleteMarkedServices(userId);
183         }
184     }
185
186     protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
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                 case PRODUCT:
223                     RestResponse product = ProductRestUtils.getProduct(i);
224                     Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
225                     allVersions = convertProductResponseToJavaObject.getAllVersions();
226                     values = allVersions.values();
227                     genericCollection.addAll(values);
228
229                     break;
230             }
231         } catch (Exception e1) {
232             e1.printStackTrace();
233         }
234     }
235
236     protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
237         RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
238         return ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
239     }
240
241     protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
242         // create new resource from Csar
243         ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
244
245         resourceDetails.setCsarUUID(csarId);
246         resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
247         RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
248         BaseRestUtils.checkCreateResponse(createResource);
249         return ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
250     }
251
252
253 }