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.log4j.Logger;
41 import org.apache.tinkerpop.gremlin.structure.Direction;
42 import org.apache.tinkerpop.gremlin.structure.Vertex;
43 import org.junit.rules.TestName;
44 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
45 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
46 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
47 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
48 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
49 import org.openecomp.sdc.be.model.Component;
50 import org.openecomp.sdc.be.model.Product;
51 import org.openecomp.sdc.be.model.Resource;
52 import org.openecomp.sdc.be.model.Service;
53 import org.openecomp.sdc.be.model.User;
54 import org.openecomp.sdc.ci.tests.config.Config;
55 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
56 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
57 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
58 import org.openecomp.sdc.ci.tests.utils.Utils;
59 import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
60 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
61 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
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.LoggerFactory;
70 import org.testng.ITestContext;
71 import org.testng.ITestResult;
72 import org.testng.annotations.*;
74 import com.aventstack.extentreports.ExtentTest;
75 import com.aventstack.extentreports.Status;
76 import com.thinkaurelius.titan.core.TitanFactory;
77 import com.thinkaurelius.titan.core.TitanGraph;
78 import com.thinkaurelius.titan.core.TitanVertex;
80 import ch.qos.logback.classic.Level;
81 import ch.qos.logback.classic.LoggerContext;
83 public abstract class ComponentBaseTest {
85 // private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName());
87 protected static Logger logger= Logger.getLogger(ComponentBaseTest.class);
90 // public ComponentBaseTest(TestName testName, String className) {
91 // super(testName, className);
94 protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
95 private static final String VERSIONS_INFO_FILE_NAME = "versions.info";
96 private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
97 protected static TitanGraph titanGraph;
98 public static Config config;
99 protected static ITestContext myContext;
103 /**************** METHODS ****************/
104 public static ExtentTest getExtendTest() {
105 return ExtentTestManager.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 // TODO Auto-generated constructor stub
114 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
115 lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
116 lc.getLogger("com.datastax").setLevel(Level.INFO);
117 lc.getLogger("io.netty").setLevel(Level.INFO);
118 lc.getLogger("c.d").setLevel(Level.INFO);
121 public static String getReportFolder() {
122 return REPORT_FOLDER;
125 @BeforeSuite(alwaysRun = true)
126 public void setupBeforeSuite(ITestContext context) throws Exception {
127 config = Utils.getConfig();
129 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
130 AtomicOperationUtils.createDefaultConsumer(true);
138 @BeforeMethod(alwaysRun = true)
139 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
142 boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
143 String className = method.getDeclaringClass().getName();
144 if (emptyDataProvider && !className.contains("ToscaValidationTest") ) {
145 System.out.println("ExtentReport instance started from BeforeMethod...");
146 String suiteName = ExtentManager.getSuiteName(context);
147 ExtentTestManager.startTest(method.getName());
148 ExtentTestManager.assignCategory(this.getClass());
151 System.out.println("ExtentReport instance started from Test...");
157 @AfterMethod(alwaysRun = true)
158 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
160 String testName = result.getName();
161 Throwable throwable = result.getThrowable();
162 int status = result.getStatus();
165 case ITestResult.SUCCESS:
166 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
169 case ITestResult.FAILURE:
170 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
171 getExtendTest().log(Status.ERROR, result.getThrowable());
172 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
175 case ITestResult.SKIP:
176 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
183 ExtentTestManager.endTest();
188 @AfterClass(alwaysRun = true)
189 public synchronized static void cleanAfterClass() throws Exception{
191 // System.out.println("<<<<<<<<class name>>>>>"+method.getDeclaringClass());
192 // System.out.println("<<<<<<<<class name>>>>>"+method.getName());
195 System.out.println("delete components AfterClass");
196 deleteCreatedComponents(getCatalogAsMap());
197 // extentReport.flush();
201 @AfterSuite(alwaysRun = true)
202 public static void shutdownTitan() throws Exception {
205 shutdownTitanLogic();
209 protected static void openTitanLogic() throws Exception {
211 logger.trace(config.toString());
212 String titanConfigFilePath = config.getTitanPropertiesFile();
213 titanGraph = TitanFactory.open(titanConfigFilePath);
214 assertNotNull(titanGraph);
219 protected static void shutdownTitanLogic() {
220 if (titanGraph.isOpen()) {
223 CassandraUtils.close();
228 public void setLog(String fromDataProvider) {
230 String suiteName = ExtentManager.getSuiteName(myContext);
231 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
232 ExtentTestManager.assignCategory(this.getClass());
236 protected static void performClean() throws Exception, FileNotFoundException {
237 // cleanComponents();
238 deleteCreatedComponents(getCatalogAsMap());
239 CassandraUtils.truncateAllKeyspaces();
242 public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
243 assertNotNull("check response object is not null after " + action, response);
244 assertNotNull("check error code exists in response after " + action, response.getErrorCode());
245 assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
248 private static void cleanComponents() throws Exception {
250 // Components to delete
251 List<String> vfResourcesToDelete = new ArrayList<String>();
252 List<String> nonVfResourcesToDelete = new ArrayList<String>();
253 List<String> servicesToDelete = new ArrayList<String>();
254 List<String> productsToDelete = new ArrayList<String>();
256 // Categories to delete
257 List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
258 List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
259 List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
260 List<String> productCategoriesToDelete = new ArrayList<>();
261 List<String> resourceCategoriesToDelete = new ArrayList<String>();
262 List<String> serviceCategoriesToDelete = new ArrayList<String>();
264 List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
265 List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
266 List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
268 Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
269 if (vertices != null) {
270 Iterator<TitanVertex> iter = vertices.iterator();
271 while (iter.hasNext()) {
272 Vertex vertex = iter.next();
273 Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
274 // if (!isAbstract) {
275 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
276 String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());
278 if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) {
279 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
280 String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
281 if (name.startsWith("ci")) {
282 if (resourceType.equals(ResourceTypeEnum.VF.name())) {
283 vfResourcesToDelete.add(id);
285 nonVfResourcesToDelete.add(id);
288 } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) {
289 if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
290 vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
296 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
297 if (vertices != null) {
298 Iterator<TitanVertex> iter = vertices.iterator();
299 while (iter.hasNext()) {
300 Vertex vertex = iter.next();
301 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
302 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
303 if (name.startsWith("ci")) {
304 servicesToDelete.add(id);
309 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
310 if (vertices != null) {
311 Iterator<TitanVertex> iter = vertices.iterator();
312 while (iter.hasNext()) {
313 Vertex vertex = iter.next();
314 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
315 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
316 if (name.startsWith("Ci")) {
317 productsToDelete.add(id);
322 // Getting categories
324 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices();
325 if (vertices != null) {
326 Iterator<TitanVertex> iter = vertices.iterator();
327 while (iter.hasNext()) {
328 Vertex category = iter.next();
329 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
330 if (!resourceCategoriesNotToDelete.contains(name)) {
331 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
332 resourceCategoriesToDelete.add(catId);
333 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
334 while (subs.hasNext()) {
335 Vertex sub = subs.next();
336 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
337 resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
343 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
344 if (vertices != null) {
345 Iterator<TitanVertex> iter = vertices.iterator();
346 while (iter.hasNext()) {
347 Vertex category = iter.next();
348 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
349 if (!serviceCategoriesNotToDelete.contains(name)) {
350 String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
351 serviceCategoriesToDelete.add(id);
356 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices();
357 if (vertices != null) {
358 Iterator<TitanVertex> iter = vertices.iterator();
359 while (iter.hasNext()) {
360 Vertex category = iter.next();
361 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
362 productCategoriesToDelete.add(catId);
363 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
364 while (subs.hasNext()) {
365 Vertex sub = subs.next();
366 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
367 productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
368 Iterator<Vertex> groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty());
369 while (groupings.hasNext()) {
370 Vertex grouping = groupings.next();
371 String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
372 productGroupingsToDelete.add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
379 titanGraph.tx().commit();
381 String adminId = UserRoleEnum.ADMIN.getUserId();
382 String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();
385 for (String id : productsToDelete) {
386 RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);
389 for (String id : servicesToDelete) {
390 RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);
393 for (String id : vfResourcesToDelete) {
394 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
398 for (String id : nonVfResourcesToDelete) {
399 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
403 // Categories delete - product
404 String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
405 for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
406 CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
408 for (ImmutablePair<String, String> pair : productSubsToDelete) {
409 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType);
411 for (String id : productCategoriesToDelete) {
412 CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
415 // Categories delete - resource
416 componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
417 for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
418 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
420 for (String id : resourceCategoriesToDelete) {
421 CategoryRestUtils.deleteCategory(id, adminId, componentType);
423 // Categories delete - resource
424 componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
425 for (String id : serviceCategoriesToDelete) {
426 CategoryRestUtils.deleteCategory(id, adminId, componentType);
431 private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
432 final String userId = UserRoleEnum.DESIGNER.getUserId();
434 List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
435 if (resourcesArrayList.size() > 0) {
436 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
437 for (String uId : collect) {
438 ProductRestUtils.deleteProduct(uId, userId);
443 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
444 if (resourcesArrayList.size() > 0) {
445 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
446 for (String uId : collect) {
447 ServiceRestUtils.markServiceToDelete(uId, userId);
449 ServiceRestUtils.deleteMarkedServices(userId);
453 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
455 // List<String> collect = resourcesArrayList.stream().filter(s ->
456 // s.getName().startsWith("ci")).map(e ->
457 // e.getUniqueId()).collect(Collectors.toList());
459 // List<Map<String, String>> collect =
460 // resourcesArrayList.stream().filter(s ->
461 // s.getName().startsWith("ci")).map(e ->
462 // e.getAllVersions()).collect(Collectors.toList());
464 * List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList());
467 if (!CollectionUtils.isEmpty(resourcesArrayList)) {
468 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
469 for (String uId : collect) {
470 ResourceRestUtils.markResourceToDelete(uId, userId);
472 ResourceRestUtils.deleteMarkedResources(userId);
479 private void deleteCollection(List<Component> componentArrayList, Consumer<String> deleteHandler) {
481 if (componentArrayList.size() > 0) {
482 List<String> collect = buildCollectionUniqueId(componentArrayList);
483 for (String uId : collect) {
484 deleteHandler.accept(uId);
485 // ProductRestUtils.deleteProduct(uId, userId);
490 protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
492 // Stream<String> flatMap = resourcesArrayList.stream().filter(s ->
493 // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e ->
494 // e.values()).flatMap( e -> e.stream());
496 // List<String> collect = resourcesArrayList.stream()
498 // .filter(s -> s.getName().startsWith("ci") )
500 // .map(e -> e.getUniqueId())
502 // .map( e -> e.values())
503 // .filter(out -> out!=null )
504 // .flatMap( e -> e.stream())
505 // .collect(Collectors.toList());
507 // List<String> collect = resourcesArrayList.stream().filter(s ->
508 // s.getName().startsWith("ci"))
510 // e.getAllVersions().values().stream()).collect(Collectors.toList());
511 ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
513 List<String> genericCollection = new ArrayList<String>();
515 resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> {
516 buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
522 // List<String> collect =
523 // genericCollection.stream().collect(Collectors.toList());
525 return genericCollection;
528 public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
529 List<String> genericCollection, String i) {
531 switch (componentTypeEnum) {
533 RestResponse resource = ResourceRestUtils.getResource(i);
534 Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
535 Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
536 Collection<String> values = allVersions.values();
537 genericCollection.addAll(values);
541 RestResponse service = ServiceRestUtils.getService(i);
542 Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
543 allVersions = convertServiceResponseToJavaObject.getAllVersions();
544 values = allVersions.values();
545 genericCollection.addAll(values);
551 RestResponse product = ProductRestUtils.getProduct(i);
552 Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
553 allVersions = convertProductResponseToJavaObject.getAllVersions();
554 values = allVersions.values();
555 genericCollection.addAll(values);
562 } catch (Exception e1) {
563 // TODO Auto-generated catch block
564 e1.printStackTrace();
568 protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
569 RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
570 Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
571 return convertCatalogResponseToJavaObject;
573 protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
574 // create new resource from Csar
575 ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
577 resourceDetails.setCsarUUID(csarId);
578 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
579 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
580 BaseRestUtils.checkCreateResponse(createResource);
581 Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
582 return createdResource;