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 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.TitanFactory;
28 import com.thinkaurelius.titan.core.TitanGraph;
29 import com.thinkaurelius.titan.core.TitanVertex;
30 import org.apache.commons.collections.CollectionUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.apache.commons.lang3.tuple.ImmutableTriple;
33 import org.apache.log4j.Logger;
34 import org.apache.tinkerpop.gremlin.structure.Direction;
35 import org.apache.tinkerpop.gremlin.structure.Vertex;
36 import org.junit.rules.TestName;
37 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
38 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
39 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
40 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
41 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
42 import org.openecomp.sdc.be.model.*;
43 import org.openecomp.sdc.ci.tests.config.Config;
44 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
45 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
46 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
47 import org.openecomp.sdc.ci.tests.utils.Utils;
48 import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
49 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
50 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
51 import org.openecomp.sdc.ci.tests.utils.rest.*;
52 import org.slf4j.LoggerFactory;
53 import org.testng.ITestContext;
54 import org.testng.ITestResult;
55 import org.testng.annotations.*;
58 import java.io.FileNotFoundException;
59 import java.io.IOException;
61 import java.util.function.Consumer;
62 import java.util.stream.Collectors;
64 import static org.testng.AssertJUnit.assertEquals;
65 import static org.testng.AssertJUnit.assertNotNull;
67 public abstract class ComponentBaseTest {
69 // private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName());
71 protected static Logger logger= Logger.getLogger(ComponentBaseTest.class);
74 // public ComponentBaseTest(TestName testName, String className) {
75 // super(testName, className);
78 protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
79 private static final String VERSIONS_INFO_FILE_NAME = "versions.info";
80 private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
81 protected static TitanGraph titanGraph;
82 public static Config config;
83 protected static ITestContext myContext;
87 /**************** METHODS ****************/
88 public static ExtentTest getExtendTest() {
89 return ExtentTestManager.getTest();
92 public static enum ComponentOperationEnum {
93 CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
96 public ComponentBaseTest(TestName name, String name2) {
97 // TODO Auto-generated constructor stub
98 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
99 lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
100 lc.getLogger("com.datastax").setLevel(Level.INFO);
101 lc.getLogger("io.netty").setLevel(Level.INFO);
102 lc.getLogger("c.d").setLevel(Level.INFO);
105 public static String getReportFolder() {
106 return REPORT_FOLDER;
109 @BeforeSuite(alwaysRun = true)
110 public void setupBeforeSuite(ITestContext context) throws Exception {
111 config = Utils.getConfig();
113 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
114 AtomicOperationUtils.createDefaultConsumer(true);
122 @BeforeMethod(alwaysRun = true)
123 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
126 // String suiteName = ExtentManager.getSuiteName(context);
127 // ExtentTestManager.startTest(method.getName());
128 // ExtentTestManager.assignCategory(this.getClass());
130 boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
131 String className = method.getDeclaringClass().getName();
132 if (!method.getName().equals("onboardVNFShotFlow")) {
133 System.out.println("ExtentReport instance started from BeforeMethod...");
134 ExtentTestManager.startTest(method.getName());
135 ExtentTestManager.assignCategory(this.getClass());
138 System.out.println("ExtentReport instance started from Test...");
144 @AfterMethod(alwaysRun = true)
145 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
147 String testName = result.getName();
148 Throwable throwable = result.getThrowable();
149 int status = result.getStatus();
152 case ITestResult.SUCCESS:
153 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
156 case ITestResult.FAILURE:
157 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
158 getExtendTest().log(Status.ERROR, result.getThrowable());
159 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
162 case ITestResult.SKIP:
163 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
170 ExtentTestManager.endTest();
175 @AfterClass(alwaysRun = true)
176 public synchronized static void cleanAfterClass() throws Exception{
178 System.out.println("delete components AfterClass");
179 deleteCreatedComponents(getCatalogAsMap());
183 @AfterSuite(alwaysRun = true)
184 public static void shutdownTitan() throws Exception {
187 shutdownTitanLogic();
191 protected static void openTitanLogic() throws Exception {
193 logger.trace(config.toString());
194 String titanConfigFilePath = config.getTitanPropertiesFile();
195 titanGraph = TitanFactory.open(titanConfigFilePath);
196 assertNotNull(titanGraph);
201 protected static void shutdownTitanLogic() {
202 if (titanGraph.isOpen()) {
205 CassandraUtils.close();
210 public void setLog(String fromDataProvider) {
212 String suiteName = ExtentManager.getSuiteName(myContext);
213 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
214 ExtentTestManager.assignCategory(this.getClass());
218 protected static void performClean() throws Exception, FileNotFoundException {
219 // cleanComponents();
220 deleteCreatedComponents(getCatalogAsMap());
221 CassandraUtils.truncateAllKeyspaces();
224 public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
225 assertNotNull("check response object is not null after " + action, response);
226 assertNotNull("check error code exists in response after " + action, response.getErrorCode());
227 assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
230 private static void cleanComponents() throws Exception {
232 // Components to delete
233 List<String> vfResourcesToDelete = new ArrayList<String>();
234 List<String> nonVfResourcesToDelete = new ArrayList<String>();
235 List<String> servicesToDelete = new ArrayList<String>();
236 List<String> productsToDelete = new ArrayList<String>();
238 // Categories to delete
239 List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
240 List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
241 List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
242 List<String> productCategoriesToDelete = new ArrayList<>();
243 List<String> resourceCategoriesToDelete = new ArrayList<String>();
244 List<String> serviceCategoriesToDelete = new ArrayList<String>();
246 List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
247 List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
248 List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
250 Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
251 if (vertices != null) {
252 Iterator<TitanVertex> iter = vertices.iterator();
253 while (iter.hasNext()) {
254 Vertex vertex = iter.next();
255 Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
256 // if (!isAbstract) {
257 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
258 String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());
260 if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) {
261 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
262 String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
263 if (name.startsWith("ci")) {
264 if (resourceType.equals(ResourceTypeEnum.VF.name())) {
265 vfResourcesToDelete.add(id);
267 nonVfResourcesToDelete.add(id);
270 } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) {
271 if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
272 vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
278 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
279 if (vertices != null) {
280 Iterator<TitanVertex> iter = vertices.iterator();
281 while (iter.hasNext()) {
282 Vertex vertex = iter.next();
283 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
284 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
285 if (name.startsWith("ci")) {
286 servicesToDelete.add(id);
291 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
292 if (vertices != null) {
293 Iterator<TitanVertex> iter = vertices.iterator();
294 while (iter.hasNext()) {
295 Vertex vertex = iter.next();
296 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
297 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
298 if (name.startsWith("Ci")) {
299 productsToDelete.add(id);
304 // Getting categories
306 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices();
307 if (vertices != null) {
308 Iterator<TitanVertex> iter = vertices.iterator();
309 while (iter.hasNext()) {
310 Vertex category = iter.next();
311 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
312 if (!resourceCategoriesNotToDelete.contains(name)) {
313 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
314 resourceCategoriesToDelete.add(catId);
315 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
316 while (subs.hasNext()) {
317 Vertex sub = subs.next();
318 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
319 resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
325 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
326 if (vertices != null) {
327 Iterator<TitanVertex> iter = vertices.iterator();
328 while (iter.hasNext()) {
329 Vertex category = iter.next();
330 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
331 if (!serviceCategoriesNotToDelete.contains(name)) {
332 String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
333 serviceCategoriesToDelete.add(id);
338 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices();
339 if (vertices != null) {
340 Iterator<TitanVertex> iter = vertices.iterator();
341 while (iter.hasNext()) {
342 Vertex category = iter.next();
343 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
344 productCategoriesToDelete.add(catId);
345 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
346 while (subs.hasNext()) {
347 Vertex sub = subs.next();
348 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
349 productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
350 Iterator<Vertex> groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty());
351 while (groupings.hasNext()) {
352 Vertex grouping = groupings.next();
353 String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
354 productGroupingsToDelete.add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
361 titanGraph.tx().commit();
363 String adminId = UserRoleEnum.ADMIN.getUserId();
364 String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();
367 for (String id : productsToDelete) {
368 RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);
371 for (String id : servicesToDelete) {
372 RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);
375 for (String id : vfResourcesToDelete) {
376 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
380 for (String id : nonVfResourcesToDelete) {
381 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
385 // Categories delete - product
386 String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
387 for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
388 CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
390 for (ImmutablePair<String, String> pair : productSubsToDelete) {
391 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType);
393 for (String id : productCategoriesToDelete) {
394 CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
397 // Categories delete - resource
398 componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
399 for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
400 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
402 for (String id : resourceCategoriesToDelete) {
403 CategoryRestUtils.deleteCategory(id, adminId, componentType);
405 // Categories delete - resource
406 componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
407 for (String id : serviceCategoriesToDelete) {
408 CategoryRestUtils.deleteCategory(id, adminId, componentType);
413 private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
414 final String userId = UserRoleEnum.DESIGNER.getUserId();
416 List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
417 if (resourcesArrayList.size() > 0) {
418 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
419 for (String uId : collect) {
420 ProductRestUtils.deleteProduct(uId, userId);
425 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
426 if (resourcesArrayList.size() > 0) {
427 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
428 for (String uId : collect) {
429 ServiceRestUtils.markServiceToDelete(uId, userId);
431 ServiceRestUtils.deleteMarkedServices(userId);
435 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
437 // List<String> collect = resourcesArrayList.stream().filter(s ->
438 // s.getName().startsWith("ci")).map(e ->
439 // e.getUniqueId()).collect(Collectors.toList());
441 // List<Map<String, String>> collect =
442 // resourcesArrayList.stream().filter(s ->
443 // s.getName().startsWith("ci")).map(e ->
444 // e.getAllVersions()).collect(Collectors.toList());
446 * List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList());
449 if (!CollectionUtils.isEmpty(resourcesArrayList)) {
450 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
451 for (String uId : collect) {
452 ResourceRestUtils.markResourceToDelete(uId, userId);
454 ResourceRestUtils.deleteMarkedResources(userId);
461 private void deleteCollection(List<Component> componentArrayList, Consumer<String> deleteHandler) {
463 if (componentArrayList.size() > 0) {
464 List<String> collect = buildCollectionUniqueId(componentArrayList);
465 for (String uId : collect) {
466 deleteHandler.accept(uId);
467 // ProductRestUtils.deleteProduct(uId, userId);
472 protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
474 // Stream<String> flatMap = resourcesArrayList.stream().filter(s ->
475 // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e ->
476 // e.values()).flatMap( e -> e.stream());
478 // List<String> collect = resourcesArrayList.stream()
480 // .filter(s -> s.getName().startsWith("ci") )
482 // .map(e -> e.getUniqueId())
484 // .map( e -> e.values())
485 // .filter(out -> out!=null )
486 // .flatMap( e -> e.stream())
487 // .collect(Collectors.toList());
489 // List<String> collect = resourcesArrayList.stream().filter(s ->
490 // s.getName().startsWith("ci"))
492 // e.getAllVersions().values().stream()).collect(Collectors.toList());
493 ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
495 List<String> genericCollection = new ArrayList<String>();
497 resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> {
498 buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
504 // List<String> collect =
505 // genericCollection.stream().collect(Collectors.toList());
507 return genericCollection;
510 public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
511 List<String> genericCollection, String i) {
513 switch (componentTypeEnum) {
515 RestResponse resource = ResourceRestUtils.getResource(i);
516 Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
517 Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
518 Collection<String> values = allVersions.values();
519 genericCollection.addAll(values);
523 RestResponse service = ServiceRestUtils.getService(i);
524 Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
525 allVersions = convertServiceResponseToJavaObject.getAllVersions();
526 values = allVersions.values();
527 genericCollection.addAll(values);
533 RestResponse product = ProductRestUtils.getProduct(i);
534 Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
535 allVersions = convertProductResponseToJavaObject.getAllVersions();
536 values = allVersions.values();
537 genericCollection.addAll(values);
544 } catch (Exception e1) {
545 // TODO Auto-generated catch block
546 e1.printStackTrace();
550 protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
551 RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
552 Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
553 return convertCatalogResponseToJavaObject;
555 protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
556 // create new resource from Csar
557 ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
559 resourceDetails.setCsarUUID(csarId);
560 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
561 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
562 BaseRestUtils.checkCreateResponse(createResource);
563 Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
564 return createdResource;