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.io.FileUtils;
32 import org.apache.commons.lang3.tuple.ImmutablePair;
33 import org.apache.commons.lang3.tuple.ImmutableTriple;
34 import org.apache.log4j.Logger;
35 import org.apache.tinkerpop.gremlin.structure.Direction;
36 import org.apache.tinkerpop.gremlin.structure.Vertex;
37 import org.junit.rules.TestName;
38 import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
39 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
40 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
41 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
42 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
43 import org.openecomp.sdc.be.model.*;
44 import org.openecomp.sdc.ci.tests.config.Config;
45 import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails;
46 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
47 import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse;
48 import org.openecomp.sdc.ci.tests.utils.Utils;
49 import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils;
50 import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils;
51 import org.openecomp.sdc.ci.tests.utils.general.ElementFactory;
52 import org.openecomp.sdc.ci.tests.utils.general.FileHandling;
53 import org.openecomp.sdc.ci.tests.utils.rest.*;
54 import org.slf4j.LoggerFactory;
55 import org.testng.ITestContext;
56 import org.testng.ITestResult;
57 import org.testng.annotations.*;
60 import java.io.FileNotFoundException;
61 import java.io.IOException;
63 import java.util.function.Consumer;
64 import java.util.stream.Collectors;
66 import static org.testng.AssertJUnit.assertEquals;
67 import static org.testng.AssertJUnit.assertNotNull;
69 public abstract class ComponentBaseTest {
71 // private static Logger logger = LoggerFactory.getLogger(ComponentBaseTest.class.getName());
73 protected static Logger logger= Logger.getLogger(ComponentBaseTest.class);
76 // public ComponentBaseTest(TestName testName, String className) {
77 // super(testName, className);
80 protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
81 private static final String VERSIONS_INFO_FILE_NAME = "versions.info";
82 private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html";
83 protected static TitanGraph titanGraph;
84 public static Config config;
85 protected static ITestContext myContext;
89 /**************** METHODS ****************/
90 public static ExtentTest getExtendTest() {
91 return ExtentTestManager.getTest();
94 public static enum ComponentOperationEnum {
95 CREATE_COMPONENT, UPDATE_COMPONENT, GET_COMPONENT, DELETE_COMPONENT, CHANGE_STATE_CHECKIN, CHANGE_STATE_CHECKOUT, CHANGE_STATE_UNDO_CHECKOUT
98 public ComponentBaseTest(TestName name, String name2) {
99 // TODO Auto-generated constructor stub
100 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
101 lc.getLogger("com.thinkaurelius").setLevel(Level.INFO);
102 lc.getLogger("com.datastax").setLevel(Level.INFO);
103 lc.getLogger("io.netty").setLevel(Level.INFO);
104 lc.getLogger("c.d").setLevel(Level.INFO);
107 public static String getReportFolder() {
108 return REPORT_FOLDER;
111 @BeforeSuite(alwaysRun = true)
112 public void setupBeforeSuite(ITestContext context) throws Exception {
113 config = Utils.getConfig();
115 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
116 AtomicOperationUtils.createDefaultConsumer(true);
124 @BeforeMethod(alwaysRun = true)
125 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
128 // String suiteName = ExtentManager.getSuiteName(context);
129 // ExtentTestManager.startTest(method.getName());
130 // ExtentTestManager.assignCategory(this.getClass());
132 boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
133 String className = method.getDeclaringClass().getName();
134 System.out.println(" method.getName() " + method.getName());
135 if (!method.getName().equals("onboardVNFShotFlow")) {
136 System.out.println("ExtentReport instance started from BeforeMethod...");
137 ExtentTestManager.startTest(method.getName());
138 ExtentTestManager.assignCategory(this.getClass());
141 System.out.println("ExtentReport instance started from Test...");
147 @AfterMethod(alwaysRun = true)
148 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
150 String testName = result.getName();
151 Throwable throwable = result.getThrowable();
152 int status = result.getStatus();
155 case ITestResult.SUCCESS:
156 getExtendTest().log(Status.PASS, "Test Result : <span class='label success'>Success</span>");
159 case ITestResult.FAILURE:
160 getExtendTest().log(Status.ERROR, "ERROR - The following exepction occured");
161 getExtendTest().log(Status.ERROR, result.getThrowable());
162 getExtendTest().log(Status.FAIL, "<span class='label failure'>Failure</span>");
165 case ITestResult.SKIP:
166 getExtendTest().log(Status.SKIP, "SKIP - The following exepction occured");
173 ExtentTestManager.endTest();
178 @AfterClass(alwaysRun = true)
179 public synchronized static void cleanAfterClass() throws Exception{
181 System.out.println("delete components AfterClass");
182 deleteCreatedComponents(getCatalogAsMap());
186 @AfterSuite(alwaysRun = true)
187 public static void shutdownTitan() throws Exception {
190 shutdownTitanLogic();
191 String basePath = FileHandling.getBasePath();
192 String csarDir = FileHandling.getCreateDirByName("outputCsar");
193 FileUtils.cleanDirectory(new File(csarDir));
198 protected static void openTitanLogic() throws Exception {
200 logger.trace(config.toString());
201 String titanConfigFilePath = config.getTitanPropertiesFile();
202 titanGraph = TitanFactory.open(titanConfigFilePath);
203 assertNotNull(titanGraph);
208 protected static void shutdownTitanLogic() {
209 if (titanGraph.isOpen()) {
212 CassandraUtils.close();
217 public void setLog(String fromDataProvider) {
219 String suiteName = ExtentManager.getSuiteName(myContext);
220 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
221 ExtentTestManager.assignCategory(this.getClass());
225 protected static void performClean() throws Exception, FileNotFoundException {
226 // cleanComponents();
227 deleteCreatedComponents(getCatalogAsMap());
228 CassandraUtils.truncateAllKeyspaces();
231 public void verifyErrorCode(RestResponse response, String action, int expectedCode) {
232 assertNotNull("check response object is not null after " + action, response);
233 assertNotNull("check error code exists in response after " + action, response.getErrorCode());
234 assertEquals("Check response code after + action" + action, expectedCode, response.getErrorCode().intValue());
237 private static void cleanComponents() throws Exception {
239 // Components to delete
240 List<String> vfResourcesToDelete = new ArrayList<String>();
241 List<String> nonVfResourcesToDelete = new ArrayList<String>();
242 List<String> servicesToDelete = new ArrayList<String>();
243 List<String> productsToDelete = new ArrayList<String>();
245 // Categories to delete
246 List<ImmutableTriple<String, String, String>> productGroupingsToDelete = new ArrayList<>();
247 List<ImmutablePair<String, String>> productSubsToDelete = new ArrayList<>();
248 List<ImmutablePair<String, String>> resourceSubsToDelete = new ArrayList<>();
249 List<String> productCategoriesToDelete = new ArrayList<>();
250 List<String> resourceCategoriesToDelete = new ArrayList<String>();
251 List<String> serviceCategoriesToDelete = new ArrayList<String>();
253 List<String> resourcesNotToDelete = config.getResourcesNotToDelete();
254 List<String> resourceCategoriesNotToDelete = config.getResourceCategoriesNotToDelete();
255 List<String> serviceCategoriesNotToDelete = config.getServiceCategoriesNotToDelete();
257 Iterable<TitanVertex> vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Resource.getName()).vertices();
258 if (vertices != null) {
259 Iterator<TitanVertex> iter = vertices.iterator();
260 while (iter.hasNext()) {
261 Vertex vertex = iter.next();
262 Boolean isAbstract = vertex.value(GraphPropertiesDictionary.IS_ABSTRACT.getProperty());
263 // if (!isAbstract) {
264 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
265 String version = vertex.value(GraphPropertiesDictionary.VERSION.getProperty());
267 if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && !version.equals("1.0"))) {
268 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
269 String resourceType = vertex.value(GraphPropertiesDictionary.RESOURCE_TYPE.getProperty());
270 if (name.startsWith("ci")) {
271 if (resourceType.equals(ResourceTypeEnum.VF.name())) {
272 vfResourcesToDelete.add(id);
274 nonVfResourcesToDelete.add(id);
277 } else if ((resourcesNotToDelete != null && !resourcesNotToDelete.contains(name)) || (version != null && version.equals("1.0"))) {
278 if ((boolean) vertex.value(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty()) == false) {
279 vertex.property(GraphPropertiesDictionary.IS_HIGHEST_VERSION.getProperty(), true);
285 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Service.getName()).vertices();
286 if (vertices != null) {
287 Iterator<TitanVertex> iter = vertices.iterator();
288 while (iter.hasNext()) {
289 Vertex vertex = iter.next();
290 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
291 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
292 if (name.startsWith("ci")) {
293 servicesToDelete.add(id);
298 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.Product.getName()).vertices();
299 if (vertices != null) {
300 Iterator<TitanVertex> iter = vertices.iterator();
301 while (iter.hasNext()) {
302 Vertex vertex = iter.next();
303 String id = vertex.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
304 String name = vertex.value(GraphPropertiesDictionary.NAME.getProperty());
305 if (name.startsWith("Ci")) {
306 productsToDelete.add(id);
311 // Getting categories
313 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ResourceNewCategory.getName()).vertices();
314 if (vertices != null) {
315 Iterator<TitanVertex> iter = vertices.iterator();
316 while (iter.hasNext()) {
317 Vertex category = iter.next();
318 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
319 if (!resourceCategoriesNotToDelete.contains(name)) {
320 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
321 resourceCategoriesToDelete.add(catId);
322 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
323 while (subs.hasNext()) {
324 Vertex sub = subs.next();
325 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
326 resourceSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
332 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ServiceNewCategory.getName()).vertices();
333 if (vertices != null) {
334 Iterator<TitanVertex> iter = vertices.iterator();
335 while (iter.hasNext()) {
336 Vertex category = iter.next();
337 String name = category.value(GraphPropertiesDictionary.NAME.getProperty());
338 if (!serviceCategoriesNotToDelete.contains(name)) {
339 String id = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
340 serviceCategoriesToDelete.add(id);
345 vertices = titanGraph.query().has(GraphPropertiesDictionary.LABEL.getProperty(), NodeTypeEnum.ProductCategory.getName()).vertices();
346 if (vertices != null) {
347 Iterator<TitanVertex> iter = vertices.iterator();
348 while (iter.hasNext()) {
349 Vertex category = iter.next();
350 String catId = category.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
351 productCategoriesToDelete.add(catId);
352 Iterator<Vertex> subs = category.vertices(Direction.OUT, GraphEdgeLabels.SUB_CATEGORY.getProperty());
353 while (subs.hasNext()) {
354 Vertex sub = subs.next();
355 String subCatId = sub.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
356 productSubsToDelete.add(new ImmutablePair<String, String>(catId, subCatId));
357 Iterator<Vertex> groupings = sub.vertices(Direction.OUT, GraphEdgeLabels.GROUPING.getProperty());
358 while (groupings.hasNext()) {
359 Vertex grouping = groupings.next();
360 String groupId = grouping.value(GraphPropertiesDictionary.UNIQUE_ID.getProperty());
361 productGroupingsToDelete.add(new ImmutableTriple<String, String, String>(catId, subCatId, groupId));
368 titanGraph.tx().commit();
370 String adminId = UserRoleEnum.ADMIN.getUserId();
371 String productStrategistId = UserRoleEnum.PRODUCT_STRATEGIST1.getUserId();
374 for (String id : productsToDelete) {
375 RestResponse deleteProduct = ProductRestUtils.deleteProduct(id, productStrategistId);
378 for (String id : servicesToDelete) {
379 RestResponse deleteServiceById = ServiceRestUtils.deleteServiceById(id, adminId);
382 for (String id : vfResourcesToDelete) {
383 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
387 for (String id : nonVfResourcesToDelete) {
388 RestResponse deleteResource = ResourceRestUtils.deleteResource(id, adminId);
392 // Categories delete - product
393 String componentType = BaseRestUtils.PRODUCT_COMPONENT_TYPE;
394 for (ImmutableTriple<String, String, String> triple : productGroupingsToDelete) {
395 CategoryRestUtils.deleteGrouping(triple.getRight(), triple.getMiddle(), triple.getLeft(), productStrategistId, componentType);
397 for (ImmutablePair<String, String> pair : productSubsToDelete) {
398 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), productStrategistId, componentType);
400 for (String id : productCategoriesToDelete) {
401 CategoryRestUtils.deleteCategory(id, productStrategistId, componentType);
404 // Categories delete - resource
405 componentType = BaseRestUtils.RESOURCE_COMPONENT_TYPE;
406 for (ImmutablePair<String, String> pair : resourceSubsToDelete) {
407 CategoryRestUtils.deleteSubCategory(pair.getRight(), pair.getLeft(), adminId, componentType);
409 for (String id : resourceCategoriesToDelete) {
410 CategoryRestUtils.deleteCategory(id, adminId, componentType);
412 // Categories delete - resource
413 componentType = BaseRestUtils.SERVICE_COMPONENT_TYPE;
414 for (String id : serviceCategoriesToDelete) {
415 CategoryRestUtils.deleteCategory(id, adminId, componentType);
420 private static void deleteCreatedComponents(Map<String, List<Component>> convertCatalogResponseToJavaObject) throws IOException {
421 final String userId = UserRoleEnum.DESIGNER.getUserId();
423 List<Component> resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.PRODUCT_PARAM_NAME);
424 if (resourcesArrayList.size() > 0) {
425 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
426 for (String uId : collect) {
427 ProductRestUtils.deleteProduct(uId, userId);
432 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.SERVICE_PARAM_NAME);
433 if (resourcesArrayList.size() > 0) {
434 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
435 for (String uId : collect) {
436 ServiceRestUtils.markServiceToDelete(uId, userId);
438 ServiceRestUtils.deleteMarkedServices(userId);
442 resourcesArrayList = convertCatalogResponseToJavaObject.get(ComponentTypeEnum.RESOURCE_PARAM_NAME);
444 // List<String> collect = resourcesArrayList.stream().filter(s ->
445 // s.getName().startsWith("ci")).map(e ->
446 // e.getUniqueId()).collect(Collectors.toList());
448 // List<Map<String, String>> collect =
449 // resourcesArrayList.stream().filter(s ->
450 // s.getName().startsWith("ci")).map(e ->
451 // e.getAllVersions()).collect(Collectors.toList());
453 * List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith("ci")) .flatMap(e -> e.getAllVersions().values().stream()).collect(Collectors.toList());
456 if (!CollectionUtils.isEmpty(resourcesArrayList)) {
457 List<String> collect = buildCollectionUniqueId(resourcesArrayList);
458 for (String uId : collect) {
459 ResourceRestUtils.markResourceToDelete(uId, userId);
461 ResourceRestUtils.deleteMarkedResources(userId);
468 private void deleteCollection(List<Component> componentArrayList, Consumer<String> deleteHandler) {
470 if (componentArrayList.size() > 0) {
471 List<String> collect = buildCollectionUniqueId(componentArrayList);
472 for (String uId : collect) {
473 deleteHandler.accept(uId);
474 // ProductRestUtils.deleteProduct(uId, userId);
479 protected static List<String> buildCollectionUniqueId(List<Component> resourcesArrayList) {
481 // Stream<String> flatMap = resourcesArrayList.stream().filter(s ->
482 // s.getName().startsWith("ci")).map(e -> e.getAllVersions()).map( e ->
483 // e.values()).flatMap( e -> e.stream());
485 // List<String> collect = resourcesArrayList.stream()
487 // .filter(s -> s.getName().startsWith("ci") )
489 // .map(e -> e.getUniqueId())
491 // .map( e -> e.values())
492 // .filter(out -> out!=null )
493 // .flatMap( e -> e.stream())
494 // .collect(Collectors.toList());
496 // List<String> collect = resourcesArrayList.stream().filter(s ->
497 // s.getName().startsWith("ci"))
499 // e.getAllVersions().values().stream()).collect(Collectors.toList());
500 ComponentTypeEnum componentTypeEnum = resourcesArrayList.get(0).getComponentType();
502 List<String> genericCollection = new ArrayList<String>();
504 resourcesArrayList.stream().filter(s -> s.getName().toLowerCase().startsWith("ci") && !s.getName().toLowerCase().equals("cindervolume")).map(e -> e.getUniqueId()).collect(Collectors.toList()).forEach((i) -> {
505 buildCollectionBaseOnComponentType(componentTypeEnum, genericCollection, i);
511 // List<String> collect =
512 // genericCollection.stream().collect(Collectors.toList());
514 return genericCollection;
517 public static void buildCollectionBaseOnComponentType(ComponentTypeEnum componentTypeEnum,
518 List<String> genericCollection, String i) {
520 switch (componentTypeEnum) {
522 RestResponse resource = ResourceRestUtils.getResource(i);
523 Resource convertResourceResponseToJavaObject = ResponseParser.convertResourceResponseToJavaObject(resource.getResponse());
524 Map<String, String> allVersions = convertResourceResponseToJavaObject.getAllVersions();
525 Collection<String> values = allVersions.values();
526 genericCollection.addAll(values);
530 RestResponse service = ServiceRestUtils.getService(i);
531 Service convertServiceResponseToJavaObject = ResponseParser.convertServiceResponseToJavaObject(service.getResponse());
532 allVersions = convertServiceResponseToJavaObject.getAllVersions();
533 values = allVersions.values();
534 genericCollection.addAll(values);
540 RestResponse product = ProductRestUtils.getProduct(i);
541 Product convertProductResponseToJavaObject = ResponseParser.convertProductResponseToJavaObject(product.getResponse());
542 allVersions = convertProductResponseToJavaObject.getAllVersions();
543 values = allVersions.values();
544 genericCollection.addAll(values);
551 } catch (Exception e1) {
552 // TODO Auto-generated catch block
553 e1.printStackTrace();
557 protected static Map<String, List<Component>> getCatalogAsMap() throws Exception {
558 RestResponse catalog = CatalogRestUtils.getCatalog(UserRoleEnum.DESIGNER.getUserId());
559 Map<String, List<Component>> convertCatalogResponseToJavaObject = ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse());
560 return convertCatalogResponseToJavaObject;
562 protected Resource createVfFromCSAR(User sdncModifierDetails, String csarId) throws Exception {
563 // create new resource from Csar
564 ResourceReqDetails resourceDetails = ElementFactory.getDefaultResource();
566 resourceDetails.setCsarUUID(csarId);
567 resourceDetails.setResourceType(ResourceTypeEnum.VF.name());
568 RestResponse createResource = ResourceRestUtils.createResource(resourceDetails, sdncModifierDetails);
569 BaseRestUtils.checkCreateResponse(createResource);
570 Resource createdResource = ResponseParser.convertResourceResponseToJavaObject(createResource.getResponse());
571 return createdResource;