Upgrade SDC from Titan to Janus Graph
[sdc.git] / test-apis-ci / src / main / java / org / openecomp / sdc / 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.openecomp.sdc.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 org.janusgraph.core.JanusGraph;
28 import org.apache.commons.collections.CollectionUtils;
29 import org.apache.log4j.Logger;
30 import org.junit.rules.TestName;
31 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
32 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
33 import org.openecomp.sdc.be.model.*;
34 import org.openecomp.sdc.ci.tests.config.Config;
35 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
36 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
37 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
38 import org.openecomp.sdc.ci.tests.utils.Utils;
39 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
40 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
41 import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
42 import org.openecomp.sdc.ci.tests.utils.rest.*;
43 import org.slf4j.LoggerFactory;
44 import org.testng.ITestContext;
45 import org.testng.ITestResult;
46 import org.testng.annotations.AfterMethod;
47 import org.testng.annotations.AfterSuite;
48 import org.testng.annotations.BeforeMethod;
49 import org.testng.annotations.BeforeSuite;
50
51 import java.io.File;
52 import java.io.FileNotFoundException;
53 import java.io.IOException;
54 import java.util.ArrayList;
55 import java.util.Collection;
56 import java.util.List;
57 import java.util.Map;
58 import java.util.stream.Collectors;
59
60 import static org.testng.AssertJUnit.assertEquals;
61 import static org.testng.AssertJUnit.assertNotNull;
62
63 public abstract class ComponentBaseTest {
64
65     protected static Logger logger = Logger.getLogger(ComponentBaseTest.class);
66
67     protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
68     private static final String VERSIONS_INFO_FILE_NAME = "versions.info";
69     private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
70     protected static JanusGraph janusGraph;
71     public static Config config;
72     protected static ITestContext myContext;
73
74
75     /**************** METHODS ****************/
76     public static ExtentTest getExtendTest() {
77         SomeInterface testManager = new ExtentTestManager();
78         return testManager.getTest();
79     }
80
81     public static enum ComponentOperationEnum {
82         CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
83     }
84
85     public ComponentBaseTest(TestName name, String name2) {
86         LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
87         lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
88         lc.getLogger("com.datastax").setLevel(Level.INFO);
89         lc.getLogger("io.netty").setLevel(Level.INFO);
90         lc.getLogger("c.d").setLevel(Level.INFO);
91     }
92
93     public static String getReportFolder() {
94         return REPORT_FOLDER;
95     }
96
97     @BeforeSuite(alwaysRun = true)
98     public void setupBeforeSuite(ITestContext context) throws Exception {
99         config = Utils.getConfig();
100         myContext = context;
101         ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
102         AtomicOperationUtils.createDefaultConsumer(true);
103         performClean();
104     }
105
106     @BeforeMethod(alwaysRun = true)
107     public void setupBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
108
109         System.out.println(" method.getName() " + method.getName());
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
122     @AfterMethod(alwaysRun = true)
123     public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
124
125         String testName = result.getName();
126         Throwable throwable = result.getThrowable();
127         int status = result.getStatus();
128
129         switch (status) {
130             case ITestResult.SUCCESS:
131                 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
132                 break;
133
134             case ITestResult.FAILURE:
135                 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
136                 getExtendTest().log(Status.ERROR, result.getThrowable());
137                 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
138                 break;
139
140             case ITestResult.SKIP:
141                 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
142                 break;
143             default:
144                 break;
145         }
146
147
148         ExtentTestManager.endTest();
149
150
151     }
152
153     @AfterSuite(alwaysRun = true)
154     public static void shutdownJanusGraph() throws Exception {
155         performClean();
156     }
157
158     public void setLog(String fromDataProvider) {
159
160         String suiteName = ExtentManager.getSuiteName(myContext);
161         ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
162         ExtentTestManager.assignCategory(this.getClass());
163
164     }
165
166     protected static void performClean() throws Exception, FileNotFoundException {
167         if (!config.getSystemUnderDebug()) {
168             deleteCreatedComponents(getCatalogAsMap());
169             FileHandling.overWriteExistindDir("outputCsar");
170         } else {
171             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 ...");
172         }
173     }
174
175     public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
176         assertNotNull("check response object is not null after " + action, response);
177         assertNotNull("check error code exists in response after " + action, response.getErrorCode());
178         assertEquals("Check response code after  + action" + action, expectedCode, response.getErrorCode().intValue());
179     }
180
181     private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
182         final String userId = UserRoleEnum.DESIGNER.getUserId();
183
184     /*    List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
185         if (resourcesArrayList.size() > 0) {
186             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
187             for (String uId : collect) {
188                 ProductRestUtils.deleteProduct(uId, userId);
189             }
190         }*/
191
192         List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
193         if (!CollectionUtils.isEmpty(resourcesArrayList)) {
194             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
195             for (String uId : collect) {
196                 ResourceRestUtils.markResourceToDelete(uId, userId);
197             }
198             ResourceRestUtils.deleteMarkedResources(userId);
199         }
200
201         resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
202         if (resourcesArrayList.size() > 0) {
203             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
204             for (String uId : collect) {
205                 ServiceRestUtils.markServiceToDelete(uId, userId);
206             }
207             ServiceRestUtils.deleteMarkedServices(userId);
208         }
209     }
210
211     protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
212
213
214         List<String> genericCollection = new ArrayList<>();
215         if(resourcesArrayList.get(0) != null) {
216             ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
217             resourcesArrayList.stream().filter(a -> a != null).
218                     filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).
219                     filter(f -> f.getUniqueId() != null).
220                     map(e -> e.getUniqueId()).
221                     collect(Collectors.toList()).
222                     forEach((i) -> {
223                         buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
224                     });
225         }
226         return genericCollection;
227     }
228
229     public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
230                                                           List<String> genericCollection, String i) {
231         try {
232             switch (componentTypeEnum) {
233                 case RESOURCE:
234                     RestResponse resource = ResourceRestUtils.getResource(i);
235                     Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
236                     Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
237                     Collection<String> values = allVersions.values();
238                     genericCollection.addAll(values);
239
240                     break;
241                 case SERVICE:
242                     RestResponse service = ServiceRestUtils.getService(i);
243                     Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
244                     allVersions = convertServiceResponseToJavaObject.getAllVersions();
245                     values = allVersions.values();
246                     genericCollection.addAll(values);
247
248                     break;
249
250
251                 case PRODUCT:
252                     RestResponse product = ProductRestUtils.getProduct(i);
253                     Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
254                     allVersions = convertProductResponseToJavaObject.getAllVersions();
255                     values = allVersions.values();
256                     genericCollection.addAll(values);
257
258                     break;
259             }
260         } catch (Exception e1) {
261             e1.printStackTrace();
262         }
263     }
264
265     protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
266         RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
267         Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
268         return convertCatalogResponseToJavaObject;
269     }
270
271     protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
272         // create new resource from Csar
273         ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
274
275         resourceDetails.setCsarUUID(csarId);
276         resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
277         RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
278         BaseRestUtils.checkCreateResponse(createResource);
279         Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
280         return createdResource;
281     }
282
283
284 }