4bb7b6162493012275231c2fd7969dca237b46b4
[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.onap.sdc.backend.ci.tests.utils.rest.BaseRestUtils;
47 import org.onap.sdc.backend.ci.tests.utils.rest.CatalogRestUtils;
48 import org.onap.sdc.backend.ci.tests.utils.rest.ProductRestUtils;
49 import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils;
50 import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser;
51 import org.onap.sdc.backend.ci.tests.utils.rest.ServiceRestUtils;
52 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
53 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
54 import org.openecomp.sdc.be.model.Component;
55 import org.openecomp.sdc.be.model.Product;
56 import org.openecomp.sdc.be.model.Resource;
57 import org.openecomp.sdc.be.model.Service;
58 import org.openecomp.sdc.be.model.User;
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 + "API" + 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
151             .startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
152         ExtentTestManager.assignCategory(this.getClass());
153     }
154
155     protected static void performClean() throws Exception {
156         if (!config.isSystemUnderDebug()) {
157             deleteCreatedComponents(getCatalogAsMap());
158             FileHandling.overWriteExistindDir("target/outputCsar");
159         } else {
160             System.out.println(
161                 "Accordindig to configuration components will not be deleted, in case to unable option to delete, please change systemUnderDebug parameter value to false ...");
162         }
163     }
164
165     private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
166         final String userId = UserRoleEnum.DESIGNER.getUserId();
167
168         List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
169         if (!CollectionUtils.isEmpty(resourcesArrayList)) {
170             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
171             for (String uId : collect) {
172                 ResourceRestUtils.markResourceToDelete(uId, userId);
173             }
174             ResourceRestUtils.deleteMarkedResources(userId);
175         }
176
177         resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
178         if (resourcesArrayList.size() > 0) {
179             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
180             for (String uId : collect) {
181                 ServiceRestUtils.markServiceToDelete(uId, userId);
182             }
183             ServiceRestUtils.deleteMarkedServices(userId);
184         }
185     }
186
187     protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
188
189         List<String> genericCollection = new ArrayList<>();
190         if (resourcesArrayList.get(0) != null) {
191             ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
192             resourcesArrayList.stream().filter(Objects::nonNull).
193                 filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).
194                 filter(f -> f.getUniqueId() != null).
195                 map(Component::getUniqueId).
196                 collect(Collectors.toList()).
197                 forEach((i) -> buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i));
198         }
199         return genericCollection;
200     }
201
202     public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
203                                                           List<String> genericCollection, String i) {
204         try {
205             switch (componentTypeEnum) {
206                 case RESOURCE:
207                     RestResponse resource = ResourceRestUtils.getResource(i);
208                     Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
209                     Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
210                     Collection<String> values = allVersions.values();
211                     genericCollection.addAll(values);
212
213                     break;
214                 case SERVICE:
215                     RestResponse service = ServiceRestUtils.getService(i);
216                     Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
217                     allVersions = convertServiceResponseToJavaObject.getAllVersions();
218                     values = allVersions.values();
219                     genericCollection.addAll(values);
220
221                     break;
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 }