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.io.FileUtils;
39 import org.apache.commons.lang3.tuple.ImmutablePair;
40 import org.apache.commons.lang3.tuple.ImmutableTriple;
41 import org.apache.log4j.Logger;
42 import org.apache.tinkerpop.gremlin.structure.Direction;
43 import org.apache.tinkerpop.gremlin.structure.Vertex;
44 import org.junit.rules.TestName;
45 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
46 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
47 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
48 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
49 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
50 import org.openecomp.sdc.be.model.Component;
51 import org.openecomp.sdc.be.model.Product;
52 import org.openecomp.sdc.be.model.Resource;
53 import org.openecomp.sdc.be.model.Service;
54 import org.openecomp.sdc.be.model.User;
55 import org.openecomp.sdc.ci.tests.config.Config;
56 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
57 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
58 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
59 import org.openecomp.sdc.ci.tests.utils.Utils;
60 import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
61 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
62 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
63 import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
64 import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils;
65 import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils;
66 import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils;
67 import org.openecomp.sdc.ci.tests.utils.rest.ProductRestUtils;
68 import org.openecomp.sdc.ci.tests.utils.rest.ResourceRestUtils;
69 import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser;
70 import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils;
71 import org.slf4j.LoggerFactory;
72 import org.testng.ITestContext;
73 import org.testng.ITestResult;
74 import org.testng.annotations.AfterClass;
75 import org.testng.annotations.AfterMethod;
76 import org.testng.annotations.AfterSuite;
77 import org.testng.annotations.BeforeMethod;
78 import org.testng.annotations.BeforeSuite;
79 import org.testng.annotations.Test;
81 import com.aventstack.extentreports.ExtentTest;
82 import com.aventstack.extentreports.Status;
83 import com.thinkaurelius.titan.core.TitanFactory;
84 import com.thinkaurelius.titan.core.TitanGraph;
85 import com.thinkaurelius.titan.core.TitanVertex;
87 import ch.qos.logback.classic.Level;
88 import ch.qos.logback.classic.LoggerContext;
90 public abstract class ComponentBaseTest {
92 // private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName());
94 protected static Logger logger= Logger.getLogger(ComponentBaseTest.class);
97 // public ComponentBaseTest(TestName testName, String className) {
98 // super(testName, className);
101 protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
102 private static final String VERSIONS_INFO_FILE_NAME = "versions.info";
103 private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
104 protected static TitanGraph titanGraph;
105 public static Config config;
106 protected static ITestContext myContext;
110 /**************** METHODS ****************/
111 public static ExtentTest getExtendTest() {
112 return ExtentTestManager.getTest();
115 public static enum ComponentOperationEnum {
116 CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
119 public ComponentBaseTest(TestName name, String name2) {
120 // TODO Auto-generated constructor stub
121 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
122 lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
123 lc.getLogger("com.datastax").setLevel(Level.INFO);
124 lc.getLogger("io.netty").setLevel(Level.INFO);
125 lc.getLogger("c.d").setLevel(Level.INFO);
128 public static String getReportFolder() {
129 return REPORT_FOLDER;
132 @BeforeSuite(alwaysRun = true)
133 public void setupBeforeSuite(ITestContext context) throws Exception {
134 config = Utils.getConfig();
136 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
137 AtomicOperationUtils.createDefaultConsumer(true);
141 String basePath = FileHandling.getBasePath();
142 String csarDir = FileHandling.getCreateDirByName("outputCsar");
143 FileUtils.cleanDirectory(new File(csarDir));
146 @BeforeMethod(alwaysRun = true)
147 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
150 // String suiteName = ExtentManager.getSuiteName(context);
151 // ExtentTestManager.startTest(method.getName());
152 // ExtentTestManager.assignCategory(this.getClass());
154 boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
155 String className = method.getDeclaringClass().getName();
156 System.out.println(" method.getName() " + method.getName());
157 if (!method.getName().equals("onboardVNFShotFlow")) {
158 System.out.println("ExtentReport instance started from BeforeMethod...");
159 ExtentTestManager.startTest(method.getName());
160 ExtentTestManager.assignCategory(this.getClass());
163 System.out.println("ExtentReport instance started from Test...");
169 @AfterMethod(alwaysRun = true)
170 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
172 String testName = result.getName();
173 Throwable throwable = result.getThrowable();
174 int status = result.getStatus();
177 case ITestResult.SUCCESS:
178 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
181 case ITestResult.FAILURE:
182 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
183 getExtendTest().log(Status.ERROR, result.getThrowable());
184 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
187 case ITestResult.SKIP:
188 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
195 ExtentTestManager.endTest();
200 @AfterClass(alwaysRun = true)
201 public synchronized static void cleanAfterClass() throws Exception{
203 System.out.println("delete components AfterClass");
204 deleteCreatedComponents(getCatalogAsMap());
208 @AfterSuite(alwaysRun = true)
209 public static void shutdownTitan() throws Exception {
212 shutdownTitanLogic();
215 protected static void openTitanLogic() throws Exception {
217 logger.trace(config.toString());
218 String titanConfigFilePath = config.getTitanPropertiesFile();
219 titanGraph = TitanFactory.open(titanConfigFilePath);
220 assertNotNull(titanGraph);
225 protected static void shutdownTitanLogic() {
226 if (titanGraph.isOpen()) {
229 CassandraUtils.close();
234 public void setLog(String fromDataProvider) {
236 String suiteName = ExtentManager.getSuiteName(myContext);
237 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
238 ExtentTestManager.assignCategory(this.getClass());
242 protected static void performClean() throws Exception, FileNotFoundException {
243 // cleanComponents();
244 deleteCreatedComponents(getCatalogAsMap());
245 CassandraUtils.truncateAllKeyspaces();
248 public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
249 assertNotNull("check response object is not null after " + action, response);
250 assertNotNull("check error code exists in response after " + action, response.getErrorCode());
251 assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
254 private static void cleanComponents() throws Exception {
256 // Components to delete
257 List<String> vfResourcesToDelete = new ArrayList<String>();
258 List<String> nonVfResourcesToDelete = new ArrayList<String>();
259 List<String> servicesToDelete = new ArrayList<String>();
260 List<String> productsToDelete = new ArrayList<String>();
262 // Categories to delete
263 List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
264 List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
265 List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
266 List<String> productCategoriesToDelete = new ArrayList<>();
267 List<String> resourceCategoriesToDelete = new ArrayList<String>();
268 List<String> serviceCategoriesToDelete = new ArrayList<String>();
270 List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
271 List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
272 List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
274 Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
275 if (vertices != null) {
276 Iterator<TitanVertex> iter = vertices.iterator();
277 while (iter.hasNext()) {
278 Vertex vertex = iter.next();
279 Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
280 // if (!isAbstract) {
281 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
282 String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());
284 if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) {
285 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
286 String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
287 if (name.startsWith("ci")) {
288 if (resourceType.equals(ResourceTypeEnum.VF.name())) {
289 vfResourcesToDelete.add(id);
291 nonVfResourcesToDelete.add(id);
294 } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) {
295 if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
296 vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
302 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
303 if (vertices != null) {
304 Iterator<TitanVertex> iter = vertices.iterator();
305 while (iter.hasNext()) {
306 Vertex vertex = iter.next();
307 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
308 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
309 if (name.startsWith("ci")) {
310 servicesToDelete.add(id);
315 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
316 if (vertices != null) {
317 Iterator<TitanVertex> iter = vertices.iterator();
318 while (iter.hasNext()) {
319 Vertex vertex = iter.next();
320 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
321 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
322 if (name.startsWith("Ci")) {
323 productsToDelete.add(id);
328 // Getting categories
330 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices();
331 if (vertices != null) {
332 Iterator<TitanVertex> iter = vertices.iterator();
333 while (iter.hasNext()) {
334 Vertex category = iter.next();
335 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
336 if (!resourceCategoriesNotToDelete.contains(name)) {
337 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
338 resourceCategoriesToDelete.add(catId);
339 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
340 while (subs.hasNext()) {
341 Vertex sub = subs.next();
342 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
343 resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
349 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
350 if (vertices != null) {
351 Iterator<TitanVertex> iter = vertices.iterator();
352 while (iter.hasNext()) {
353 Vertex category = iter.next();
354 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
355 if (!serviceCategoriesNotToDelete.contains(name)) {
356 String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
357 serviceCategoriesToDelete.add(id);
362 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices();
363 if (vertices != null) {
364 Iterator<TitanVertex> iter = vertices.iterator();
365 while (iter.hasNext()) {
366 Vertex category = iter.next();
367 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
368 productCategoriesToDelete.add(catId);
369 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
370 while (subs.hasNext()) {
371 Vertex sub = subs.next();
372 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
373 productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
374 Iterator<Vertex> groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty());
375 while (groupings.hasNext()) {
376 Vertex grouping = groupings.next();
377 String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
378 productGroupingsToDelete.add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
385 titanGraph.tx().commit();
387 String adminId = UserRoleEnum.ADMIN.getUserId();
388 String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();
391 for (String id : productsToDelete) {
392 RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);
395 for (String id : servicesToDelete) {
396 RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);
399 for (String id : vfResourcesToDelete) {
400 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
404 for (String id : nonVfResourcesToDelete) {
405 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
409 // Categories delete - product
410 String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
411 for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
412 CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
414 for (ImmutablePair<String, String> pair : productSubsToDelete) {
415 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType);
417 for (String id : productCategoriesToDelete) {
418 CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
421 // Categories delete - resource
422 componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
423 for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
424 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
426 for (String id : resourceCategoriesToDelete) {
427 CategoryRestUtils.deleteCategory(id, adminId, componentType);
429 // Categories delete - resource
430 componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
431 for (String id : serviceCategoriesToDelete) {
432 CategoryRestUtils.deleteCategory(id, adminId, componentType);
437 private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
438 final String userId = UserRoleEnum.DESIGNER.getUserId();
440 List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
441 if (resourcesArrayList.size() > 0) {
442 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
443 for (String uId : collect) {
444 ProductRestUtils.deleteProduct(uId, userId);
449 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
450 if (resourcesArrayList.size() > 0) {
451 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
452 for (String uId : collect) {
453 ServiceRestUtils.markServiceToDelete(uId, userId);
455 ServiceRestUtils.deleteMarkedServices(userId);
459 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
461 // List<String> collect = resourcesArrayList.stream().filter(s ->
462 // s.getName().startsWith("ci")).map(e ->
463 // e.getUniqueId()).collect(Collectors.toList());
465 // List<Map<String, String>> collect =
466 // resourcesArrayList.stream().filter(s ->
467 // s.getName().startsWith("ci")).map(e ->
468 // e.getAllVersions()).collect(Collectors.toList());
470 * List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList());
473 if (!CollectionUtils.isEmpty(resourcesArrayList)) {
474 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
475 for (String uId : collect) {
476 ResourceRestUtils.markResourceToDelete(uId, userId);
478 ResourceRestUtils.deleteMarkedResources(userId);
485 private void deleteCollection(List<Component> componentArrayList, Consumer<String> deleteHandler) {
487 if (componentArrayList.size() > 0) {
488 List<String> collect = buildCollectionUniqueId(componentArrayList);
489 for (String uId : collect) {
490 deleteHandler.accept(uId);
491 // ProductRestUtils.deleteProduct(uId, userId);
496 protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
498 // Stream<String> flatMap = resourcesArrayList.stream().filter(s ->
499 // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e ->
500 // e.values()).flatMap( e -> e.stream());
502 // List<String> collect = resourcesArrayList.stream()
504 // .filter(s -> s.getName().startsWith("ci") )
506 // .map(e -> e.getUniqueId())
508 // .map( e -> e.values())
509 // .filter(out -> out!=null )
510 // .flatMap( e -> e.stream())
511 // .collect(Collectors.toList());
513 // List<String> collect = resourcesArrayList.stream().filter(s ->
514 // s.getName().startsWith("ci"))
516 // e.getAllVersions().values().stream()).collect(Collectors.toList());
517 ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
519 List<String> genericCollection = new ArrayList<String>();
521 resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> {
522 buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
528 // List<String> collect =
529 // genericCollection.stream().collect(Collectors.toList());
531 return genericCollection;
534 public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
535 List<String> genericCollection, String i) {
537 switch (componentTypeEnum) {
539 RestResponse resource = ResourceRestUtils.getResource(i);
540 Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
541 Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
542 Collection<String> values = allVersions.values();
543 genericCollection.addAll(values);
547 RestResponse service = ServiceRestUtils.getService(i);
548 Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
549 allVersions = convertServiceResponseToJavaObject.getAllVersions();
550 values = allVersions.values();
551 genericCollection.addAll(values);
557 RestResponse product = ProductRestUtils.getProduct(i);
558 Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
559 allVersions = convertProductResponseToJavaObject.getAllVersions();
560 values = allVersions.values();
561 genericCollection.addAll(values);
568 } catch (Exception e1) {
569 // TODO Auto-generated catch block
570 e1.printStackTrace();
574 protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
575 RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
576 Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
577 return convertCatalogResponseToJavaObject;
579 protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
580 // create new resource from Csar
581 ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
583 resourceDetails.setCsarUUID(csarId);
584 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
585 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
586 BaseRestUtils.checkCreateResponse(createResource);
587 Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
588 return createdResource;