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 System.out.println(" method.getName() " + method.getName());
133 if (!method.getName().equals("onboardVNFShotFlow")) {
134 System.out.println("ExtentReport instance started from BeforeMethod...");
135 ExtentTestManager.startTest(method.getName());
136 ExtentTestManager.assignCategory(this.getClass());
139 System.out.println("ExtentReport instance started from Test...");
145 @AfterMethod(alwaysRun = true)
146 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
148 String testName = result.getName();
149 Throwable throwable = result.getThrowable();
150 int status = result.getStatus();
153 case ITestResult.SUCCESS:
154 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
157 case ITestResult.FAILURE:
158 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
159 getExtendTest().log(Status.ERROR, result.getThrowable());
160 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
163 case ITestResult.SKIP:
164 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
171 ExtentTestManager.endTest();
176 @AfterClass(alwaysRun = true)
177 public synchronized static void cleanAfterClass() throws Exception{
179 System.out.println("delete components AfterClass");
180 deleteCreatedComponents(getCatalogAsMap());
184 @AfterSuite(alwaysRun = true)
185 public static void shutdownTitan() throws Exception {
188 shutdownTitanLogic();
192 protected static void openTitanLogic() throws Exception {
194 logger.trace(config.toString());
195 String titanConfigFilePath = config.getTitanPropertiesFile();
196 titanGraph = TitanFactory.open(titanConfigFilePath);
197 assertNotNull(titanGraph);
202 protected static void shutdownTitanLogic() {
203 if (titanGraph.isOpen()) {
206 CassandraUtils.close();
211 public void setLog(String fromDataProvider) {
213 String suiteName = ExtentManager.getSuiteName(myContext);
214 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
215 ExtentTestManager.assignCategory(this.getClass());
219 protected static void performClean() throws Exception, FileNotFoundException {
220 // cleanComponents();
221 deleteCreatedComponents(getCatalogAsMap());
222 CassandraUtils.truncateAllKeyspaces();
225 public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
226 assertNotNull("check response object is not null after " + action, response);
227 assertNotNull("check error code exists in response after " + action, response.getErrorCode());
228 assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
231 private static void cleanComponents() throws Exception {
233 // Components to delete
234 List<String> vfResourcesToDelete = new ArrayList<String>();
235 List<String> nonVfResourcesToDelete = new ArrayList<String>();
236 List<String> servicesToDelete = new ArrayList<String>();
237 List<String> productsToDelete = new ArrayList<String>();
239 // Categories to delete
240 List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
241 List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
242 List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
243 List<String> productCategoriesToDelete = new ArrayList<>();
244 List<String> resourceCategoriesToDelete = new ArrayList<String>();
245 List<String> serviceCategoriesToDelete = new ArrayList<String>();
247 List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
248 List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
249 List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
251 Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
252 if (vertices != null) {
253 Iterator<TitanVertex> iter = vertices.iterator();
254 while (iter.hasNext()) {
255 Vertex vertex = iter.next();
256 Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
257 // if (!isAbstract) {
258 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
259 String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());
261 if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) {
262 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
263 String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
264 if (name.startsWith("ci")) {
265 if (resourceType.equals(ResourceTypeEnum.VF.name())) {
266 vfResourcesToDelete.add(id);
268 nonVfResourcesToDelete.add(id);
271 } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) {
272 if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
273 vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
279 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
280 if (vertices != null) {
281 Iterator<TitanVertex> iter = vertices.iterator();
282 while (iter.hasNext()) {
283 Vertex vertex = iter.next();
284 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
285 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
286 if (name.startsWith("ci")) {
287 servicesToDelete.add(id);
292 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
293 if (vertices != null) {
294 Iterator<TitanVertex> iter = vertices.iterator();
295 while (iter.hasNext()) {
296 Vertex vertex = iter.next();
297 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
298 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
299 if (name.startsWith("Ci")) {
300 productsToDelete.add(id);
305 // Getting categories
307 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices();
308 if (vertices != null) {
309 Iterator<TitanVertex> iter = vertices.iterator();
310 while (iter.hasNext()) {
311 Vertex category = iter.next();
312 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
313 if (!resourceCategoriesNotToDelete.contains(name)) {
314 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
315 resourceCategoriesToDelete.add(catId);
316 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
317 while (subs.hasNext()) {
318 Vertex sub = subs.next();
319 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
320 resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
326 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
327 if (vertices != null) {
328 Iterator<TitanVertex> iter = vertices.iterator();
329 while (iter.hasNext()) {
330 Vertex category = iter.next();
331 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
332 if (!serviceCategoriesNotToDelete.contains(name)) {
333 String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
334 serviceCategoriesToDelete.add(id);
339 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices();
340 if (vertices != null) {
341 Iterator<TitanVertex> iter = vertices.iterator();
342 while (iter.hasNext()) {
343 Vertex category = iter.next();
344 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
345 productCategoriesToDelete.add(catId);
346 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
347 while (subs.hasNext()) {
348 Vertex sub = subs.next();
349 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
350 productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
351 Iterator<Vertex> groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty());
352 while (groupings.hasNext()) {
353 Vertex grouping = groupings.next();
354 String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
355 productGroupingsToDelete.add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
362 titanGraph.tx().commit();
364 String adminId = UserRoleEnum.ADMIN.getUserId();
365 String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();
368 for (String id : productsToDelete) {
369 RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);
372 for (String id : servicesToDelete) {
373 RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);
376 for (String id : vfResourcesToDelete) {
377 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
381 for (String id : nonVfResourcesToDelete) {
382 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
386 // Categories delete - product
387 String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
388 for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
389 CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
391 for (ImmutablePair<String, String> pair : productSubsToDelete) {
392 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType);
394 for (String id : productCategoriesToDelete) {
395 CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
398 // Categories delete - resource
399 componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
400 for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
401 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
403 for (String id : resourceCategoriesToDelete) {
404 CategoryRestUtils.deleteCategory(id, adminId, componentType);
406 // Categories delete - resource
407 componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
408 for (String id : serviceCategoriesToDelete) {
409 CategoryRestUtils.deleteCategory(id, adminId, componentType);
414 private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
415 final String userId = UserRoleEnum.DESIGNER.getUserId();
417 List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
418 if (resourcesArrayList.size() > 0) {
419 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
420 for (String uId : collect) {
421 ProductRestUtils.deleteProduct(uId, userId);
426 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
427 if (resourcesArrayList.size() > 0) {
428 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
429 for (String uId : collect) {
430 ServiceRestUtils.markServiceToDelete(uId, userId);
432 ServiceRestUtils.deleteMarkedServices(userId);
436 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
438 // List<String> collect = resourcesArrayList.stream().filter(s ->
439 // s.getName().startsWith("ci")).map(e ->
440 // e.getUniqueId()).collect(Collectors.toList());
442 // List<Map<String, String>> collect =
443 // resourcesArrayList.stream().filter(s ->
444 // s.getName().startsWith("ci")).map(e ->
445 // e.getAllVersions()).collect(Collectors.toList());
447 * List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList());
450 if (!CollectionUtils.isEmpty(resourcesArrayList)) {
451 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
452 for (String uId : collect) {
453 ResourceRestUtils.markResourceToDelete(uId, userId);
455 ResourceRestUtils.deleteMarkedResources(userId);
462 private void deleteCollection(List<Component> componentArrayList, Consumer<String> deleteHandler) {
464 if (componentArrayList.size() > 0) {
465 List<String> collect = buildCollectionUniqueId(componentArrayList);
466 for (String uId : collect) {
467 deleteHandler.accept(uId);
468 // ProductRestUtils.deleteProduct(uId, userId);
473 protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
475 // Stream<String> flatMap = resourcesArrayList.stream().filter(s ->
476 // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e ->
477 // e.values()).flatMap( e -> e.stream());
479 // List<String> collect = resourcesArrayList.stream()
481 // .filter(s -> s.getName().startsWith("ci") )
483 // .map(e -> e.getUniqueId())
485 // .map( e -> e.values())
486 // .filter(out -> out!=null )
487 // .flatMap( e -> e.stream())
488 // .collect(Collectors.toList());
490 // List<String> collect = resourcesArrayList.stream().filter(s ->
491 // s.getName().startsWith("ci"))
493 // e.getAllVersions().values().stream()).collect(Collectors.toList());
494 ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
496 List<String> genericCollection = new ArrayList<String>();
498 resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> {
499 buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
505 // List<String> collect =
506 // genericCollection.stream().collect(Collectors.toList());
508 return genericCollection;
511 public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
512 List<String> genericCollection, String i) {
514 switch (componentTypeEnum) {
516 RestResponse resource = ResourceRestUtils.getResource(i);
517 Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
518 Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
519 Collection<String> values = allVersions.values();
520 genericCollection.addAll(values);
524 RestResponse service = ServiceRestUtils.getService(i);
525 Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
526 allVersions = convertServiceResponseToJavaObject.getAllVersions();
527 values = allVersions.values();
528 genericCollection.addAll(values);
534 RestResponse product = ProductRestUtils.getProduct(i);
535 Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
536 allVersions = convertProductResponseToJavaObject.getAllVersions();
537 values = allVersions.values();
538 genericCollection.addAll(values);
545 } catch (Exception e1) {
546 // TODO Auto-generated catch block
547 e1.printStackTrace();
551 protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
552 RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
553 Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
554 return convertCatalogResponseToJavaObject;
556 protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
557 // create new resource from Csar
558 ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
560 resourceDetails.setCsarUUID(csarId);
561 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
562 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
563 BaseRestUtils.checkCreateResponse(createResource);
564 Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
565 return createdResource;