2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.sdc.ci.tests.api;
23 import static org.testng.AssertJUnit.assertEquals;
24 import static org.testng.AssertJUnit.assertNotNull;
27 import java.io.FileNotFoundException;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Iterator;
32 import java.util.List;
34 import java.util.function.Consumer;
35 import java.util.stream.Collectors;
37 import org.apache.commons.collections.CollectionUtils;
38 import org.apache.commons.lang3.tuple.ImmutablePair;
39 import org.apache.commons.lang3.tuple.ImmutableTriple;
40 import org.apache.tinkerpop.gremlin.structure.Direction;
41 import org.apache.tinkerpop.gremlin.structure.Vertex;
42 import org.junit.rules.TestName;
43 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
44 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
45 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
46 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
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.openecomp.sdc.ci.tests.config.Config;
54 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
55 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
56 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
57 import org.openecomp.sdc.ci.tests.utils.Utils;
58 import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
59 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
60 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
61 import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
62 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
63 import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
64 import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
65 import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
66 import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
67 import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
68 import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71 import org.testng.ITestContext;
72 import org.testng.ITestResult;
73 import org.testng.annotations.AfterClass;
74 import org.testng.annotations.AfterMethod;
75 import org.testng.annotations.AfterSuite;
76 import org.testng.annotations.BeforeMethod;
77 import org.testng.annotations.BeforeSuite;
79 import com.aventstack.extentreports.ExtentTest;
80 import com.aventstack.extentreports.Status;
81 import com.thinkaurelius.titan.core.TitanFactory;
82 import com.thinkaurelius.titan.core.TitanGraph;
83 import com.thinkaurelius.titan.core.TitanVertex;
85 import ch.qos.logback.classic.Level;
86 import ch.qos.logback.classic.LoggerContext;
89 public abstract class ComponentBaseTest {
92 protected static Logger logger= LoggerFactory.getLogger(ComponentBaseTest.class);
93 protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
94 private static final String VERSIONS_INFO_FILE_NAME = "versions.info";
95 private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
96 protected static TitanGraph titanGraph;
97 public static Config config;
98 protected static ITestContext myContext;
102 /**************** METHODS ****************/
103 public static ExtentTest getExtendTest() {
104 SomeInterface testManager = new ExtentTestManager();
105 return testManager.getTest();
108 public static enum ComponentOperationEnum {
109 CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
112 public ComponentBaseTest(TestName name, String name2) {
113 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
114 lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
115 lc.getLogger("com.datastax").setLevel(Level.INFO);
116 lc.getLogger("io.netty").setLevel(Level.INFO);
117 lc.getLogger("c.d").setLevel(Level.INFO);
120 public static String getReportFolder() {
121 return REPORT_FOLDER;
124 @BeforeSuite(alwaysRun = true)
125 public void setupBeforeSuite(ITestContext context) throws Exception {
126 config = Utils.getConfig();
128 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
129 AtomicOperationUtils.createDefaultConsumer(true);
137 @BeforeMethod(alwaysRun = true)
138 public void setupBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
140 System.out.println(" method.getName() " + method.getName());
141 if (!method.getName().equals("onboardVNFShotFlow")) {
142 // System.out.println("ExtentReport instance started from BeforeMethod...");
143 logger.info("ExtentReport instance started from BeforeMethod...");
144 ExtentTestManager.startTest(method.getName());
145 ExtentTestManager.assignCategory(this.getClass());
148 // System.out.println("ExtentReport instance started from Test...");
149 logger.debug("ExtentReport instance started from Test...");
154 @AfterMethod(alwaysRun = true)
155 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
157 String testName = result.getName();
158 Throwable throwable = result.getThrowable();
159 int status = result.getStatus();
162 case ITestResult.SUCCESS:
163 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
166 case ITestResult.FAILURE:
167 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
168 getExtendTest().log(Status.ERROR, result.getThrowable());
169 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
172 case ITestResult.SKIP:
173 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
180 ExtentTestManager.endTest();
185 @AfterClass(alwaysRun = true)
186 public synchronized static void cleanAfterClass() throws Exception{
188 // System.out.println("<<<<<<<<class name>>>>>"+method.getDeclaringClass());
189 // System.out.println("<<<<<<<<class name>>>>>"+method.getName());
192 System.out.println("delete components AfterClass");
193 deleteCreatedComponents(getCatalogAsMap());
194 // extentReport.flush();
198 @AfterSuite(alwaysRun = true)
199 public static void shutdownTitan() throws Exception {
202 shutdownTitanLogic();
206 protected static void openTitanLogic() throws Exception {
208 logger.trace(config.toString());
209 String titanConfigFilePath = config.getTitanPropertiesFile();
210 titanGraph = TitanFactory.open(titanConfigFilePath);
211 assertNotNull(titanGraph);
216 protected static void shutdownTitanLogic() {
217 if (titanGraph.isOpen()) {
220 CassandraUtils.close();
225 public void setLog(String fromDataProvider) {
227 String suiteName = ExtentManager.getSuiteName(myContext);
228 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
229 ExtentTestManager.assignCategory(this.getClass());
233 protected static void performClean() throws Exception, FileNotFoundException {
234 // cleanComponents();
235 if(!config.getSystemUnderDebug()){
236 deleteCreatedComponents(getCatalogAsMap());
237 CassandraUtils.truncateAllKeyspaces();
238 FileHandling.overWriteExistindDir("outputCsar");
241 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 ...");
245 public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
246 assertNotNull("check response object is not null after " + action, response);
247 assertNotNull("check error code exists in response after " + action, response.getErrorCode());
248 assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
251 private static void cleanComponents() throws Exception {
253 // Components to delete
254 List<String> vfResourcesToDelete = new ArrayList<String>();
255 List<String> nonVfResourcesToDelete = new ArrayList<String>();
256 List<String> servicesToDelete = new ArrayList<String>();
257 List<String> productsToDelete = new ArrayList<String>();
259 // Categories to delete
260 List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
261 List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
262 List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
263 List<String> productCategoriesToDelete = new ArrayList<>();
264 List<String> resourceCategoriesToDelete = new ArrayList<String>();
265 List<String> serviceCategoriesToDelete = new ArrayList<String>();
267 List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
268 List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
269 List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
271 Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
272 if (vertices != null) {
273 Iterator<TitanVertex> iter = vertices.iterator();
274 while (iter.hasNext()) {
275 Vertex vertex = iter.next();
276 Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
277 // if (!isAbstract) {
278 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
279 String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());
281 if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) {
282 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
283 String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
284 if (name.startsWith("ci")) {
285 if (resourceType.equals(ResourceTypeEnum.VF.name())) {
286 vfResourcesToDelete.add(id);
288 nonVfResourcesToDelete.add(id);
291 } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) {
292 if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
293 vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
299 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
300 if (vertices != null) {
301 Iterator<TitanVertex> iter = vertices.iterator();
302 while (iter.hasNext()) {
303 Vertex vertex = iter.next();
304 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
305 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
306 if (name.startsWith("ci")) {
307 servicesToDelete.add(id);
312 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
313 if (vertices != null) {
314 Iterator<TitanVertex> iter = vertices.iterator();
315 while (iter.hasNext()) {
316 Vertex vertex = iter.next();
317 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
318 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
319 if (name.startsWith("Ci")) {
320 productsToDelete.add(id);
325 // Getting categories
327 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices();
328 if (vertices != null) {
329 Iterator<TitanVertex> iter = vertices.iterator();
330 while (iter.hasNext()) {
331 Vertex category = iter.next();
332 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
333 if (!resourceCategoriesNotToDelete.contains(name)) {
334 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
335 resourceCategoriesToDelete.add(catId);
336 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
337 while (subs.hasNext()) {
338 Vertex sub = subs.next();
339 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
340 resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
346 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
347 if (vertices != null) {
348 Iterator<TitanVertex> iter = vertices.iterator();
349 while (iter.hasNext()) {
350 Vertex category = iter.next();
351 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
352 if (!serviceCategoriesNotToDelete.contains(name)) {
353 String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
354 serviceCategoriesToDelete.add(id);
359 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices();
360 if (vertices != null) {
361 Iterator<TitanVertex> iter = vertices.iterator();
362 while (iter.hasNext()) {
363 Vertex category = iter.next();
364 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
365 productCategoriesToDelete.add(catId);
366 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
367 while (subs.hasNext()) {
368 Vertex sub = subs.next();
369 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
370 productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
371 Iterator<Vertex> groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty());
372 while (groupings.hasNext()) {
373 Vertex grouping = groupings.next();
374 String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
375 productGroupingsToDelete.add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
382 titanGraph.tx().commit();
384 String adminId = UserRoleEnum.ADMIN.getUserId();
385 /* String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();*/
389 /* for (String id : productsToDelete) {
390 RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);
393 for (String id : servicesToDelete) {
394 RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);
397 for (String id : vfResourcesToDelete) {
398 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
402 for (String id : nonVfResourcesToDelete) {
403 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
407 // Categories delete - product
408 /*String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
409 for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
410 CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
412 for (ImmutablePair<String, String> pair : productSubsToDelete) {
413 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType);
415 for (String id : productCategoriesToDelete) {
416 CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
419 // Categories delete - resource
420 String componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
421 for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
422 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
424 for (String id : resourceCategoriesToDelete) {
425 CategoryRestUtils.deleteCategory(id, adminId, componentType);
427 // Categories delete - resource
428 componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
429 for (String id : serviceCategoriesToDelete) {
430 CategoryRestUtils.deleteCategory(id, adminId, componentType);
435 private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
436 final String userId = UserRoleEnum.DESIGNER.getUserId();
438 List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
439 if (resourcesArrayList.size() > 0) {
440 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
441 for (String uId : collect) {
442 ProductRestUtils.deleteProduct(uId, userId);
447 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
448 if (resourcesArrayList.size() > 0) {
449 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
450 for (String uId : collect) {
451 ServiceRestUtils.markServiceToDelete(uId, userId);
453 ServiceRestUtils.deleteMarkedServices(userId);
457 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
459 // List<String> collect = resourcesArrayList.stream().filter(s ->
460 // s.getName().startsWith("ci")).map(e ->
461 // e.getUniqueId()).collect(Collectors.toList());
463 // List<Map<String, String>> collect =
464 // resourcesArrayList.stream().filter(s ->
465 // s.getName().startsWith("ci")).map(e ->
466 // e.getAllVersions()).collect(Collectors.toList());
468 * List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList());
471 if (!CollectionUtils.isEmpty(resourcesArrayList)) {
472 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
473 for (String uId : collect) {
474 ResourceRestUtils.markResourceToDelete(uId, userId);
476 ResourceRestUtils.deleteMarkedResources(userId);
483 private void deleteCollection(List<Component> componentArrayList, Consumer<String> deleteHandler) {
485 if (componentArrayList.size() > 0) {
486 List<String> collect = buildCollectionUniqueId(componentArrayList);
487 for (String uId : collect) {
488 deleteHandler.accept(uId);
489 // ProductRestUtils.deleteProduct(uId, userId);
494 protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
496 // Stream<String> flatMap = resourcesArrayList.stream().filter(s ->
497 // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e ->
498 // e.values()).flatMap( e -> e.stream());
500 // List<String> collect = resourcesArrayList.stream()
502 // .filter(s -> s.getName().startsWith("ci") )
504 // .map(e -> e.getUniqueId())
506 // .map( e -> e.values())
507 // .filter(out -> out!=null )
508 // .flatMap( e -> e.stream())
509 // .collect(Collectors.toList());
511 // List<String> collect = resourcesArrayList.stream().filter(s ->
512 // s.getName().startsWith("ci"))
514 // e.getAllVersions().values().stream()).collect(Collectors.toList());
515 ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
517 List<String> genericCollection = new ArrayList<String>();
519 resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> {
520 buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
526 // List<String> collect =
527 // genericCollection.stream().collect(Collectors.toList());
529 return genericCollection;
532 public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
533 List<String> genericCollection, String i) {
535 switch (componentTypeEnum) {
537 RestResponse resource = ResourceRestUtils.getResource(i);
538 Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
539 Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
540 Collection<String> values = allVersions.values();
541 genericCollection.addAll(values);
545 RestResponse service = ServiceRestUtils.getService(i);
546 Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
547 allVersions = convertServiceResponseToJavaObject.getAllVersions();
548 values = allVersions.values();
549 genericCollection.addAll(values);
555 RestResponse product = ProductRestUtils.getProduct(i);
556 Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
557 allVersions = convertProductResponseToJavaObject.getAllVersions();
558 values = allVersions.values();
559 genericCollection.addAll(values);
566 } catch (Exception e1) {
567 // TODO Auto-generated catch block
568 e1.printStackTrace();
572 protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
573 RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
574 Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
575 return convertCatalogResponseToJavaObject;
577 protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
578 // create new resource from Csar
579 ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
581 resourceDetails.setCsarUUID(csarId);
582 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
583 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
584 BaseRestUtils.checkCreateResponse(createResource);
585 Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
586 return createdResource;