re base code
[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 com.thinkaurelius.titan.core.TitanGraph;
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 TitanGraph titanGraph;
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 (!method.getName().equals("onboardVNFShotFlow")) {
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
121     @AfterMethod(alwaysRun = true)
122     public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
123
124         String testName = result.getName();
125         Throwable throwable = result.getThrowable();
126         int status = result.getStatus();
127
128         switch (status) {
129             case ITestResult.SUCCESS:
130                 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
131                 break;
132
133             case ITestResult.FAILURE:
134                 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
135                 getExtendTest().log(Status.ERROR, result.getThrowable());
136                 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
137                 break;
138
139             case ITestResult.SKIP:
140                 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
141                 break;
142             default:
143                 break;
144         }
145
146
147         ExtentTestManager.endTest();
148
149
150     }
151
152     @AfterSuite(alwaysRun = true)
153     public static void shutdownTitan() throws Exception {
154         performClean();
155     }
156
157     public void setLog(String fromDataProvider) {
158
159         String suiteName = ExtentManager.getSuiteName(myContext);
160         ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
161         ExtentTestManager.assignCategory(this.getClass());
162
163     }
164
165     protected static void performClean() throws Exception, FileNotFoundException {
166         if (!config.getSystemUnderDebug()) {
167             deleteCreatedComponents(getCatalogAsMap());
168             FileHandling.overWriteExistindDir("outputCsar");
169         } else {
170             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 ...");
171         }
172     }
173
174     public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
175         assertNotNull("check response object is not null after " + action, response);
176         assertNotNull("check error code exists in response after " + action, response.getErrorCode());
177         assertEquals("Check response code after  + action" + action, expectedCode, response.getErrorCode().intValue());
178     }
179
180     private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
181         final String userId = UserRoleEnum.DESIGNER.getUserId();
182
183     /*    List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
184         if (resourcesArrayList.size() > 0) {
185             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
186             for (String uId : collect) {
187                 ProductRestUtils.deleteProduct(uId, userId);
188             }
189         }*/
190
191         List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
192         if (!CollectionUtils.isEmpty(resourcesArrayList)) {
193             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
194             for (String uId : collect) {
195                 ResourceRestUtils.markResourceToDelete(uId, userId);
196             }
197             ResourceRestUtils.deleteMarkedResources(userId);
198         }
199
200         resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
201         if (resourcesArrayList.size() > 0) {
202             List<String> collect = buildCollectionUniqueId(resourcesArrayList);
203             for (String uId : collect) {
204                 ServiceRestUtils.markServiceToDelete(uId, userId);
205             }
206             ServiceRestUtils.deleteMarkedServices(userId);
207         }
208     }
209
210     protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
211
212
213         List<String> genericCollection = new ArrayList<>();
214         if(resourcesArrayList.get(0) != null) {
215             ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
216             resourcesArrayList.stream().filter(a -> a != null).
217                     filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).
218                     filter(f -> f.getUniqueId() != null).
219                     map(e -> e.getUniqueId()).
220                     collect(Collectors.toList()).
221                     forEach((i) -> {
222                         buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
223                     });
224         }
225         return genericCollection;
226     }
227
228     public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
229                                                           List<String> genericCollection, String i) {
230         try {
231             switch (componentTypeEnum) {
232                 case RESOURCE:
233                     RestResponse resource = ResourceRestUtils.getResource(i);
234                     Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
235                     Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
236                     Collection<String> values = allVersions.values();
237                     genericCollection.addAll(values);
238
239                     break;
240                 case SERVICE:
241                     RestResponse service = ServiceRestUtils.getService(i);
242                     Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
243                     allVersions = convertServiceResponseToJavaObject.getAllVersions();
244                     values = allVersions.values();
245                     genericCollection.addAll(values);
246
247                     break;
248
249
250                 case PRODUCT:
251                     RestResponse product = ProductRestUtils.getProduct(i);
252                     Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
253                     allVersions = convertProductResponseToJavaObject.getAllVersions();
254                     values = allVersions.values();
255                     genericCollection.addAll(values);
256
257                     break;
258             }
259         } catch (Exception e1) {
260             e1.printStackTrace();
261         }
262     }
263
264     protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
265         RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
266         Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
267         return convertCatalogResponseToJavaObject;
268     }
269
270     protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
271         // create new resource from Csar
272         ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
273
274         resourceDetails.setCsarUUID(csarId);
275         resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
276         RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
277         BaseRestUtils.checkCreateResponse(createResource);
278         Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
279         return createdResource;
280     }
281
282
283 }