From 6cc9a11a09a9b650442bf301eb8fd1aa6cad66bc Mon Sep 17 00:00:00 2001 From: Idan Amit Date: Wed, 13 Sep 2017 17:21:33 +0300 Subject: ComponentBaseTest.java enhancement and new onboarding class that test onboarding only And merge release/1710 branch into master Change-Id: I300d897b151010aa26f8732518fa2e3b7ed4291b Issue-Id: SDC-331 Signed-off-by: Idan Amit --- test-apis-ci/pom.xml | 14 +- .../sdc/ci/tests/api/ComponentBaseTest.java | 176 ++--- .../openecomp/sdc/ci/tests/api/ExtentManager.java | 152 +++- .../sdc/ci/tests/api/ExtentTestActions.java | 111 +++ .../sdc/ci/tests/api/ExtentTestManager.java | 14 +- .../java/org/openecomp/sdc/ci/tests/api/Urls.java | 2 + .../dataProviders/OnbordingDataProviders.java | 72 ++ .../ci/tests/datatypes/AmdocsLicenseMembers.java | 56 ++ .../sdc/ci/tests/datatypes/ResourceReqDetails.java | 25 + .../sdc/ci/tests/datatypes/ServiceReqDetails.java | 37 + .../datatypes/VendorSoftwareProductObject.java | 102 +++ .../execute/artifacts/ArtifactServletTest.java | 2 +- .../execute/artifacts/DownloadComponentArt.java | 2 +- .../DistributionDownloadArtifactTest.java | 4 +- .../execute/imports/ImportNewResourceCITest.java | 2 +- .../org/openecomp/sdc/ci/tests/sanity/Onboard.java | 126 ++++ .../ci/tests/tosca/datatypes/ToscaDefinition.java | 59 +- .../datatypes/ToscaGroupsMetadataDefinition.java | 84 --- .../ToscaGroupsTopologyTemplateDefinition.java | 6 +- .../tosca/datatypes/ToscaImportsDefinition.java | 22 +- .../ToscaInputsTopologyTemplateDefinition.java | 8 +- .../tosca/datatypes/ToscaMetadataDefinition.java | 196 +++++ .../ToscaServiceGroupsMetadataDefinition.java | 84 +++ .../model/ToscaMetadataFieldsPresentationEnum.java | 74 ++ .../sdc/ci/tests/utils/ToscaParserUtils.java | 11 +- .../tests/utils/general/AtomicOperationUtils.java | 51 +- .../sdc/ci/tests/utils/general/ElementFactory.java | 4 +- .../sdc/ci/tests/utils/general/FileHandling.java | 542 ++++++++++++++ .../utils/general/OnboardingUtillViaApis.java | 293 ++++++++ .../ci/tests/utils/general/OnboardingUtils.java | 799 +++++++++++++++++++++ .../sdc/ci/tests/utils/general/SnmpTypeEnum.java | 88 +++ .../sdc/ci/tests/utils/rest/ResourceRestUtils.java | 4 +- .../utils/rest/ResourceRestUtilsExternalAPI.java | 2 +- .../sdc/externalApis/CRUDExternalAPI.java | 2 +- 34 files changed, 2946 insertions(+), 280 deletions(-) create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AmdocsLicenseMembers.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java delete mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsMetadataDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaMetadataDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/model/ToscaMetadataFieldsPresentationEnum.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtillViaApis.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java create mode 100644 test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java (limited to 'test-apis-ci') diff --git a/test-apis-ci/pom.xml b/test-apis-ci/pom.xml index 7184c8b06f..14e1fc3fcd 100644 --- a/test-apis-ci/pom.xml +++ b/test-apis-ci/pom.xml @@ -226,8 +226,8 @@ - com.thinkaurelius.titan - titan-cassandra + org.openecomp.sdc.sdc-titan-cassandra + sdc-titan-cassandra ${titan.version} compile @@ -277,10 +277,16 @@ json 20090211 - + + + org.openecomp.sdc.sdc-tosca + sdc-tosca + 1.1.32-SNAPSHOT compile diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java index a9cc119b20..cfd132d5d0 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ComponentBaseTest.java @@ -35,7 +35,6 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.apache.log4j.Logger; @@ -60,7 +59,6 @@ import org.openecomp.sdc.ci.tests.utils.Utils; import org.openecomp.sdc.ci.tests.utils.cassandra.CassandraUtils; import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; -import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils; import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; import org.openecomp.sdc.ci.tests.utils.rest.CatalogRestUtils; import org.openecomp.sdc.ci.tests.utils.rest.CategoryRestUtils; @@ -71,13 +69,8 @@ import org.openecomp.sdc.ci.tests.utils.rest.ServiceRestUtils; import org.slf4j.LoggerFactory; import org.testng.ITestContext; import org.testng.ITestResult; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.AfterSuite; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.BeforeSuite; +import org.testng.annotations.*; -import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; import com.aventstack.extentreports.Status; import com.thinkaurelius.titan.core.TitanFactory; @@ -94,17 +87,16 @@ public abstract class ComponentBaseTest { protected static Logger logger= Logger.getLogger(ComponentBaseTest.class); - // public ComponentBaseTest(TestName testName, String className) { - // super(testName, className); - // } +// public ComponentBaseTest(TestName testName, String className) { +// super(testName, className); +// } - protected static ExtentReports extentReport; - public static final String REPORT_FOLDER = "./ExtentReport/"; + protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator; private static final String VERSIONS_INFO_FILE_NAME = "versions.info"; private static final String REPORT_FILE_NAME = "SDC_CI_Extent_Report.html"; protected static TitanGraph titanGraph; - private static Config myconfig; public static Config config; + protected static ITestContext myContext; @@ -125,104 +117,45 @@ public abstract class ComponentBaseTest { lc.getLogger("io.netty").setLevel(Level.INFO); lc.getLogger("c.d").setLevel(Level.INFO); } + + public static String getReportFolder() { + return REPORT_FOLDER; + } @BeforeSuite(alwaysRun = true) - public static void openTitan(ITestContext context) throws Exception { - - logger.info("<<>>"); - myconfig = Utils.getConfig(); + public void setupBeforeSuite(ITestContext context) throws Exception { config = Utils.getConfig(); - - File dir = new File(REPORT_FOLDER); - try { - FileUtils.deleteDirectory(dir); - } catch (IOException e) { - } - dir.mkdir(); - - System.out.println("BeforeSuite - get reporter"); - extentReport = ExtentManager.getReporter(REPORT_FOLDER + REPORT_FILE_NAME); - - String onboardVersion = AutomationUtils.getOnboardVersion(); - String osVersion = AutomationUtils.getOSVersion(); - String envData = myconfig.getUrl(); - // TODO: uncomment config file -// extentReport.loadConfig(AutomationUtils.getConfigFile(CONFIG_FILE)); - - extentReport.setSystemInfo("Onboard Version", onboardVersion); - extentReport.setSystemInfo("OS Version", osVersion); - extentReport.setSystemInfo("ExecutedOn", envData); - extentReport.setSystemInfo("SuiteName", context.getName()); - AutomationUtils.createVersionsInfoFile(REPORT_FOLDER + VERSIONS_INFO_FILE_NAME, onboardVersion, osVersion, envData); - - System.out.println("BeforeSuite - open titan"); - openTitanLogic(); - - System.out.println("BeforeSuite - createConsumer"); + myContext=context; + ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context); AtomicOperationUtils.createDefaultConsumer(true); - - System.out.println("BeforeSuite - performClean"); + openTitanLogic(); performClean(); - } - - protected static void openTitanLogic() throws Exception { - - logger.trace(config.toString()); - String titanConfigFilePath = myconfig.getTitanPropertiesFile(); - titanGraph = TitanFactory.open(titanConfigFilePath); - assertNotNull(titanGraph); - - } - - @AfterClass(alwaysRun = true) - public synchronized static void cleanAfterClass() throws Exception{ - -// System.out.println("<<<<<<<>>>>"+method.getDeclaringClass()); -// System.out.println("<<<<<<<>>>>"+method.getName()); - System.out.println("delete components AfterClass"); - deleteCreatedComponents(getCatalogAsMap()); -// extentReport.flush(); } - @AfterSuite(alwaysRun = true) - public static void shutdownTitan() throws Exception { - - System.out.println("AfterSuite - flush report"); - extentReport.flush(); - System.out.println("AfterSuite - perform clean"); - performClean(); - System.out.println("AfterSuite - close report"); -// extentReport.close(); - System.out.println("AfterSuite - close titan"); - shutdownTitanLogic(); - System.out.println("AfterSuite - suite ended"); - } - - protected static void shutdownTitanLogic() { - if (titanGraph.isOpen()) { - titanGraph.close(); - } - CassandraUtils.close(); - } - @BeforeMethod(alwaysRun = true) - public void beforeState(java.lang.reflect.Method method) throws Exception { - - - ExtentTestManager.startTest(method.getName()); - String[] parts = this.getClass().getName().toString().split("\\."); - String lastOne1 = parts[parts.length-1]; - String lastOne2 = parts[parts.length-2]; - getExtendTest().assignCategory(lastOne2 + "-" + lastOne1); - getExtendTest().log(Status.INFO, "Test started"); + public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception { + + + boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty(); + String className = method.getDeclaringClass().getName(); + if (emptyDataProvider && !className.contains("ToscaValidationTest") ) { + System.out.println("ExtentReport instance started from BeforeMethod..."); + String suiteName = ExtentManager.getSuiteName(context); + ExtentTestManager.startTest(method.getName()); + ExtentTestManager.assignCategory(this.getClass()); + + } else { + System.out.println("ExtentReport instance started from Test..."); + } + } @AfterMethod(alwaysRun = true) - public void afterState(ITestResult result) throws Exception { + public void quitAfterTest(ITestResult result, ITestContext context) throws Exception { String testName = result.getName(); Throwable throwable = result.getThrowable(); @@ -248,8 +181,55 @@ public abstract class ComponentBaseTest { ExtentTestManager.endTest(); - extentReport.flush(); + + + } + + @AfterClass(alwaysRun = true) + public synchronized static void cleanAfterClass() throws Exception{ + +// System.out.println("<<<<<<<>>>>"+method.getDeclaringClass()); +// System.out.println("<<<<<<<>>>>"+method.getName()); + + + System.out.println("delete components AfterClass"); + deleteCreatedComponents(getCatalogAsMap()); +// extentReport.flush(); + + } + + @AfterSuite(alwaysRun = true) + public static void shutdownTitan() throws Exception { + + performClean(); + shutdownTitanLogic(); + + } + + protected static void openTitanLogic() throws Exception { + + logger.trace(config.toString()); + String titanConfigFilePath = config.getTitanPropertiesFile(); + titanGraph = TitanFactory.open(titanConfigFilePath); + assertNotNull(titanGraph); + } + + + protected static void shutdownTitanLogic() { + if (titanGraph.isOpen()) { + titanGraph.close(); + } + CassandraUtils.close(); + } + + + + public void setLog(String fromDataProvider) { + + String suiteName = ExtentManager.getSuiteName(myContext); + ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + "      " + fromDataProvider); + ExtentTestManager.assignCategory(this.getClass()); } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java index 2b970fd8a1..ae16f7406e 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentManager.java @@ -20,53 +20,149 @@ package org.openecomp.sdc.ci.tests.api; -import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils; - import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.reporter.ExtentHtmlReporter; import com.aventstack.extentreports.reporter.ExtentXReporter; import com.aventstack.extentreports.reporter.configuration.Protocol; import com.aventstack.extentreports.reporter.configuration.Theme; +import org.openecomp.sdc.ci.tests.config.Config; + +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.general.FileHandling; +import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils; +import org.testng.ITestContext; + +import java.io.File; public class ExtentManager { + + private static final String VERSIONS_INFO_FILE_NAME = "versions.info"; + private static ExtentReports extent; + private static ExtentHtmlReporter htmlReporter; + private static ExtentXReporter extentxReporter; + private static final String icon = "$(document).ready(function() {" +"\n"+ + "$('.brand-logo').html('').prepend(\"\").width(\"120px\").css(\"float\",\"left\").css(\"padding-left\",\"0\");$('.report-name').css(\"font-weight\",\"bold\");"+"\n"+ +// "$('.logo-content' ).remove();"+"\n"+ +// "$('#slide-out li:first-child').on('click', function(){ $('#charts-row').hide() }) ; $('#slide-out li:last-child').on('click', function(){ $('#charts-row').show() });"+"\n"+ +// "$('.charts div:nth-child(2)').remove();"+"\n"+ + "})"; - private static ExtentReports extent; + public enum suiteNameXml { + + TESTNG_FAILED_XML_NAME("testng-failed.xml"); + + suiteNameXml(String value) { + this.value = value; + } + + private String value; + + public String getValue() { + return value; + } + + } - public synchronized static ExtentReports getReporter(String filePath) { - if (extent == null) { - // initialize the HtmlReporter - ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(filePath); - - // initialize ExtentReports and attach the HtmlReporter - extent = new ExtentReports(); + public synchronized static ExtentReports setReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception { + String dbIp = Utils.getConfig().getReportDBhost(); + int dbPort = Utils.getConfig().getReportDBport(); - // attach all reporters - extent.attachReporter(htmlReporter); - - + if (extent == null) { + extentxReporter = new ExtentXReporter(dbIp, dbPort); + extent = new ExtentReports(); + initAndSetExtentHtmlReporter(filePath, htmlFile, isAppend); + + if(extentxReporter.config().getReportObjectId() != null){ + setExtentXReporter(isAppend); + }else{ + extentxReporter.stop(); + } } - return extent; } - public synchronized static ExtentHtmlReporter setConfiguration(ExtentHtmlReporter htmlReporter) { + public synchronized static void setExtentXReporter(Boolean isAppend){ + extentxReporter.setAppendExisting(isAppend); + extent.attachReporter(extentxReporter); + } + + public synchronized static void initAndSetExtentHtmlReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception{ + htmlReporter = new ExtentHtmlReporter(filePath + htmlFile); + setConfiguration(htmlReporter); + htmlReporter.setAppendExisting(isAppend); + extent.attachReporter(htmlReporter); + } + + public synchronized static ExtentReports getReporter() { + return extent; + } + + public static void initReporter(String filepath, String htmlFile, ITestContext context) throws Exception { + + String onboardVersion = AutomationUtils.getOnboardVersion(); + String osVersion = AutomationUtils.getOSVersion(); + Config config = Utils.getConfig(); + String envData = config.getUrl(); + String suiteName = getSuiteName(context); + + if(suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())){ + if (config.getUseBrowserMobProxy()) + setTrafficCaptue(config); + + setReporter(filepath, htmlFile, true); + String suiteNameFromVersionInfoFile = FileHandling.getKeyByValueFromPropertyFormatFile(filepath + VERSIONS_INFO_FILE_NAME, "suiteName"); + reporterDataDefinition(onboardVersion, osVersion, envData, suiteNameFromVersionInfoFile); + }else{ + FileHandling.deleteDirectory(ComponentBaseTest.getReportFolder()); + FileHandling.createDirectory(filepath); + setReporter(filepath, htmlFile, false); + reporterDataDefinition(onboardVersion, osVersion, envData, suiteName); + AutomationUtils.createVersionsInfoFile(filepath + VERSIONS_INFO_FILE_NAME, onboardVersion, osVersion, envData, suiteName); + } + + } + + public static void reporterDataDefinition(String onboardVersion, String osVersion, String envData, String suiteNameFromVersionInfoFile) throws Exception { + extent.setSystemInfo("Onboard Version", onboardVersion); + extent.setSystemInfo("OS Version", osVersion); +// extent.setSystemInfo("Host Name Address", RestCDUtils.getExecutionHostAddress()); + extent.setSystemInfo("ExecutedOn", envData); + extent.setSystemInfo("SuiteName", suiteNameFromVersionInfoFile); + } + + public static String getSuiteName(ITestContext context) { + String suitePath = context.getSuite().getXmlSuite().getFileName(); + if(suitePath != null){ + File file = new File(suitePath); + String suiteName = file.getName(); + return suiteName; + } + return null; + } + + public synchronized static ExtentHtmlReporter setConfiguration(ExtentHtmlReporter htmlReporter) throws Exception { + htmlReporter.config().setTheme(Theme.STANDARD); - htmlReporter.config().setEncoding("UTF-8"); - htmlReporter.config().setProtocol(Protocol.HTTPS); - - htmlReporter.config().setDocumentTitle("ASDC Automation Report"); - + htmlReporter.config().setDocumentTitle("SDC Automation Report"); htmlReporter.config().setChartVisibilityOnOpen(true); - - htmlReporter.config().setReportName(AutomationUtils.getOSVersion()); - +// htmlReporter.config().setReportName(AutomationUtils.getATTVersion()); + htmlReporter.config().setReportName("SDC Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(false); + htmlReporter.config().setJS(icon); return htmlReporter; } - - public synchronized static ExtentReports getReporter() { - return extent; - } + + public static void closeReporter(){ + extent.flush(); + } + + public static void setTrafficCaptue(Config config) { + boolean mobProxyStatus = config.getUseBrowserMobProxy(); + if (mobProxyStatus){ + config.setCaptureTraffic(true);; + } + } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java new file mode 100644 index 0000000000..f865ef1699 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestActions.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.api; + +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.MediaEntityBuilder; +import com.aventstack.extentreports.Status; +import com.aventstack.extentreports.markuputils.ExtentColor; +import com.aventstack.extentreports.markuputils.Markup; +import com.aventstack.extentreports.markuputils.MarkupHelper; + +import java.io.File; + + +public class ExtentTestActions { + + public static void log(Status logStatus, Markup mark){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, mark); + } + + public static void log(Status logStatus, String message){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, message); + } + + public static void log(Status logStatus, String message, String duration){ + log(logStatus, message + addDurationTag(duration)); + } + + public static void log(Status logStatus, Throwable throwabel){ + ExtentTest test = ExtentTestManager.getTest(); + test.log(logStatus, throwabel); + } + + public static void addTag(Status logStatus, String message){ + Markup m = null; + switch(logStatus){ + case PASS: + m = MarkupHelper.createLabel(message, ExtentColor.GREEN); + break; + case FAIL: + m = MarkupHelper.createLabel(message, ExtentColor.RED); + break; + case SKIP: + m = MarkupHelper.createLabel(message, ExtentColor.BLUE); + break; + case FATAL: + m = MarkupHelper.createLabel(message, ExtentColor.BROWN); + break; + default: + break; + } + + if (m != null){ + log(logStatus, m); + } + } + +// public static String addScreenshot(Status logStatus, String screenshotName, String message) throws IOException{ +// String imageFilePath = null; +// String uuid = UUID.randomUUID().toString(); +// String[] stringArray = uuid.split("-"); +// screenshotName = screenshotName + "-" + stringArray[stringArray.length - 1]; +// try { +// File imageFile = GeneralUIUtils.takeScreenshot(screenshotName, SetupCDTest.getScreenshotFolder()); +// imageFilePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFile.toURI()).getPath(); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// +// ExtentTest test = ExtentTestManager.getTest(); +// test.log(logStatus, message, MediaEntityBuilder.createScreenCaptureFromPath(imageFilePath).build()); +// return imageFilePath; +// } + + private static String addDurationTag(String duration){ + return "" + duration + ""; + } + + public static String addLinkTag(String fileName, String pathToFile){ + return String.format("HAR file", fileName, pathToFile); + } + + public static void addFileToReportAsLink(File harFile, String pathToFileFromReportDirectory, String message) { + log(Status.INFO, message, addLinkTag(harFile.getName(), pathToFileFromReportDirectory)); + } + + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java index 9c4acd4367..3d8c6a999e 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/ExtentTestManager.java @@ -20,11 +20,10 @@ package org.openecomp.sdc.ci.tests.api; -import java.util.HashMap; - import com.aventstack.extentreports.ExtentReports; import com.aventstack.extentreports.ExtentTest; +import java.util.HashMap; public class ExtentTestManager { @@ -37,8 +36,6 @@ public class ExtentTestManager { public static synchronized void endTest() { // extent.endTest(extentTestMap.get(Thread.currentThread().getId())); -// extentTestMap.get(Thread.currentThread().getId()); // This is test - // TODO: maybe uncomment becuase we will need it only at the end extent.flush(); } @@ -52,5 +49,14 @@ public class ExtentTestManager { return test; } + + public static synchronized void assignCategory(Class clazz){ + String[] parts = clazz.getName().split("\\."); + String lastOne1 = parts[parts.length-1]; + String lastOne2 = parts[parts.length-2]; + getTest().assignCategory(lastOne2 + "-" + lastOne1); + } + + } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java index ea1c9eff8d..15a1eb783a 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/api/Urls.java @@ -364,5 +364,7 @@ public interface Urls { final String ONBOARD_VERSION = "http://%s:%s/onboarding-api/docs/build-info.json"; final String OS_VERSION = "http://%s:%s/sdc2/rest/version"; +// amdocs APIs + final String GET_VENDOR_SOFTWARE_PRODUCT = "http://%s:%s/onboarding-api/v1.0/vendor-software-products/packages/%s"; } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java new file mode 100644 index 0000000000..8b58ca9993 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/dataProviders/OnbordingDataProviders.java @@ -0,0 +1,72 @@ +package org.openecomp.sdc.ci.tests.dataProviders; + +import org.openecomp.sdc.ci.tests.utils.general.FileHandling; +import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtils; +import org.testng.annotations.DataProvider; + + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class OnbordingDataProviders { + + protected static String filepath = FileHandling.getVnfRepositoryPath(); + +// -----------------------dataProviders----------------------------------------- + @DataProvider(name = "randomVNF_List", parallel = false) + private static final Object[][] randomVnfList() throws Exception { + int randomElementNumber = 3; //how many VNFs to onboard randomly + List fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List newRandomFileNamesFromFolder = getRandomElements(randomElementNumber, fileNamesFromFolder); + System.out.println(String.format("There are %s zip file(s) to test", newRandomFileNamesFromFolder.size())); + return provideData(newRandomFileNamesFromFolder, filepath); + } + + @DataProvider(name = "VNF_List" , parallel = true) + private static final Object[][] VnfList() throws Exception { + + List fileNamesFromFolder = OnboardingUtils.getVnfNamesFileList(); + + System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.size())); + return provideData(fileNamesFromFolder, filepath); + } + +// -----------------------factories----------------------------------------- + + + + +// -----------------------methods----------------------------------------- + public static Object[][] provideData(List fileNamesFromFolder, String filepath) { + + Object[][] arObject = new Object[fileNamesFromFolder.size()][]; + int index = 0; + for (Object obj : fileNamesFromFolder) { + arObject[index++] = new Object[] { filepath, obj }; + } + return arObject; + } + + private static List getRandomElements(int randomElementNumber, List fileNamesFromFolder) { + if(fileNamesFromFolder.size() == 0 || fileNamesFromFolder.size() < randomElementNumber){ + return null; + }else{ + List indexList = new ArrayList<>(); + List newRandomFileNamesFromFolder = new ArrayList<>(); + for(int i = 0; i < fileNamesFromFolder.size(); i++){ + indexList.add(i); + } + Collections.shuffle(indexList); + Integer[] randomArray = indexList.subList(0, randomElementNumber).toArray(new Integer[randomElementNumber]); + for(int i = 0; i < randomArray.length; i++){ + newRandomFileNamesFromFolder.add(fileNamesFromFolder.get(randomArray[i])); + } + return newRandomFileNamesFromFolder; + } + } + + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AmdocsLicenseMembers.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AmdocsLicenseMembers.java new file mode 100644 index 0000000000..9c2cfa809c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/AmdocsLicenseMembers.java @@ -0,0 +1,56 @@ +package org.openecomp.sdc.ci.tests.datatypes; + +public class AmdocsLicenseMembers { + + private String vendorId; + private String vendorLicenseName; + private String vendorLicenseAgreementId; + private String featureGroupId; + + public AmdocsLicenseMembers(String vendorId, String vendorLicenseName, String vendorLicenseAgreementId, String featureGroupId) { + super(); + this.vendorId = vendorId; + this.vendorLicenseName = vendorLicenseName; + this.vendorLicenseAgreementId = vendorLicenseAgreementId; + this.featureGroupId = featureGroupId; + } + + public String getVendorId() { + return vendorId; + } + + public void setVendorId(String vendorId) { + this.vendorId = vendorId; + } + + public String getVendorLicenseName() { + return vendorLicenseName; + } + + public void setVendorLicenseName(String vendorLicenseName) { + this.vendorLicenseName = vendorLicenseName; + } + + public String getVendorLicenseAgreementId() { + return vendorLicenseAgreementId; + } + + public void setVendorLicenseAgreementId(String vendorLicenseAgreementId) { + this.vendorLicenseAgreementId = vendorLicenseAgreementId; + } + + public String getFeatureGroupId() { + return featureGroupId; + } + + public void setFeatureGroupId(String featureGroupId) { + this.featureGroupId = featureGroupId; + } + + @Override + public String toString() { + return "AmdocsLicenseMembers [vendorId=" + vendorId + ", vendorLicenseName=" + vendorLicenseName + ", vendorLicenseAgreementId=" + vendorLicenseAgreementId + ", featureGroupId=" + featureGroupId + "]"; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java index 8456e5b35b..5a80fd14ca 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ResourceReqDetails.java @@ -35,8 +35,10 @@ public class ResourceReqDetails extends ComponentReqDetails { Boolean isAbstract; Boolean isHighestVersion; String cost; + String licenseType; String toscaResourceName; + String resourceVendorModelNumber; private String resourceType = ResourceTypeEnum.VFC.toString(); // Default // value @@ -45,6 +47,21 @@ public class ResourceReqDetails extends ComponentReqDetails { super(); } + public ResourceReqDetails(List derivedFrom, String vendorName, String vendorRelease, Boolean isAbstract, Boolean isHighestVersion, String cost, String licenseType, String toscaResourceName, String resourceVendorModelNumber, + String resourceType) { + super(); + this.derivedFrom = derivedFrom; + this.vendorName = vendorName; + this.vendorRelease = vendorRelease; + this.isAbstract = isAbstract; + this.isHighestVersion = isHighestVersion; + this.cost = cost; + this.licenseType = licenseType; + this.toscaResourceName = toscaResourceName; + this.resourceVendorModelNumber = resourceVendorModelNumber; + this.resourceType = resourceType; + } + public ResourceReqDetails(Resource resource) { super(); this.resourceType = resource.getResourceType().toString(); @@ -68,6 +85,7 @@ public class ResourceReqDetails extends ComponentReqDetails { this.UUID = resource.getUUID(); this.categories = resource.getCategories(); this.importedToscaChecksum = resource.getImportedToscaChecksum(); + this.resourceVendorModelNumber = resource.getResourceVendorModelNumber(); } @@ -136,6 +154,13 @@ public class ResourceReqDetails extends ComponentReqDetails { this.toscaResourceName = resourceName; } + public String getResourceVendorModelNumber() { + return resourceVendorModelNumber; + } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber) { + this.resourceVendorModelNumber = resourceVendorModelNumber; + } public String getToscaResourceName() { return toscaResourceName; } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java index e33183ca94..2f3d648ef6 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/ServiceReqDetails.java @@ -26,6 +26,43 @@ import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.category.CategoryDefinition; public class ServiceReqDetails extends ComponentReqDetails { + + protected String serviceType; + protected String serviceRole; + protected String namingPolicy; + protected Boolean ecompGeneratedNaming; + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public String getNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + + public Boolean getEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + + public void setEcompGeneratedNaming(Boolean ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + } public ServiceReqDetails(String serviceName, String category, ArrayList tags, String description, String contactId, String icon) { diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java new file mode 100644 index 0000000000..fbdb88e712 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/datatypes/VendorSoftwareProductObject.java @@ -0,0 +1,102 @@ +package org.openecomp.sdc.ci.tests.datatypes; + +public class VendorSoftwareProductObject { + + private String vendorName; + private String vspId; + private String category; + private String subCategory; + private String componentId; + private String description; + private String attContact; + private String vspName; + + public VendorSoftwareProductObject() { + super(); + // TODO Auto-generated constructor stub + } + + public VendorSoftwareProductObject(String vendorName, String vspId, String category, String subCategory, String componentId, String description, String attContact) { + super(); + this.vendorName = vendorName; + this.vspId = vspId; + this.category = category; + this.subCategory = subCategory; + this.componentId = componentId; + this.description = description; + this.attContact = attContact; + } + + + public String getVspName() { + return vspName; + } + + public void setVspName(String vspName) { + this.vspName = vspName; + } + + public String getVendorName() { + return vendorName; + } + + public void setVendorName(String vendorName) { + this.vendorName = vendorName; + } + + public String getVspId() { + return vspId; + } + + public void setVspId(String vspId) { + this.vspId = vspId; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubCategory() { + return subCategory; + } + + public void setSubCategory(String subCategory) { + this.subCategory = subCategory; + } + + public String getComponentId() { + return componentId; + } + + public void setComponentId(String componentId) { + this.componentId = componentId; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getAttContact() { + return attContact; + } + + public void setAttContact(String attContact) { + this.attContact = attContact; + } + + @Override + public String toString() { + return "VendorSoftwareProductObject [vendorName=" + vendorName + ", vspId=" + vspId + ", category=" + category + ", subCategory=" + subCategory + ", componentId=" + componentId + ", description=" + description + ", attContact=" + + attContact + "]"; + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java index 7e363202bb..1f578d108c 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/ArtifactServletTest.java @@ -311,7 +311,7 @@ public class ArtifactServletTest extends ComponentBaseTest { httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); if (addMd5Header) { - httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody)); + httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5Base64EncodedByString(jsonBody)); } StringEntity input = new StringEntity(jsonBody); input.setContentType("application/json"); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java index bb2b662009..5f1230f4ce 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/artifacts/DownloadComponentArt.java @@ -624,7 +624,7 @@ artifact.setArtifactLabel("configure");*/ httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); if (addMd5Header) { - httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody)); + httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5Base64EncodedByString(jsonBody)); } StringEntity input = new StringEntity(jsonBody); input.setContentType("application/json"); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java index 7ba705fc7d..258619292f 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/distribution/DistributionDownloadArtifactTest.java @@ -212,7 +212,7 @@ public class DistributionDownloadArtifactTest extends ComponentBaseTest { AssertJUnit.assertEquals(artifactDetails.getPayload(), Base64.encodeBase64String(actualContents.getBytes())); // validating checksum - String actualPayloadChecksum = GeneralUtility.calculateMD5ByByteArray(actualContents.getBytes()); + String actualPayloadChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(actualContents.getBytes()); AssertJUnit.assertEquals(expectedPayloadChecksum, actualPayloadChecksum); // validate audit @@ -380,7 +380,7 @@ public class DistributionDownloadArtifactTest extends ComponentBaseTest { // validating checksum byte[] bytes = actualContents.getBytes(); - String actualPayloadChecksum = GeneralUtility.calculateMD5ByByteArray(bytes); + String actualPayloadChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(bytes); assertEquals(expectedPayloadChecksum, actualPayloadChecksum); // validating valid zip diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java index c069f984d2..56deb3e08b 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/execute/imports/ImportNewResourceCITest.java @@ -189,7 +189,7 @@ public class ImportNewResourceCITest extends ComponentBaseTest { + " \"icon\": \"router\",\r\n" + " \"tags\": [\r\n" + " \"importResource4test\"\r\n" + " ],\r\n" + " \"payloadData\": \"" + encodedPayload + "\"\r\n" + "}"; - String md5 = GeneralUtility.calculateMD5ByString(json); + String md5 = GeneralUtility.calculateMD5Base64EncodedByString(json); Map headers = new HashMap(); headers.put(Constants.MD5_HEADER, md5); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java new file mode 100644 index 0000000000..2b341f5cbf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/sanity/Onboard.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.sanity; + + + + + +import org.junit.Rule; +import org.junit.rules.TestName; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.api.ExtentTestActions; +import org.openecomp.sdc.ci.tests.dataProviders.OnbordingDataProviders; +import org.openecomp.sdc.ci.tests.datatypes.ResourceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.ServiceReqDetails; +import org.openecomp.sdc.ci.tests.datatypes.VendorSoftwareProductObject; +import org.openecomp.sdc.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.ci.tests.utils.general.OnboardingUtillViaApis; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +import fj.data.Either; + + + + + + +public class Onboard extends ComponentBaseTest { + + + @Rule + public static TestName name = new TestName(); + + public Onboard() { + super(name, Onboard.class.getName()); + } + + protected String makeDistributionValue; + + + + @Parameters({ "makeDistribution" }) + @BeforeMethod + public void beforeTestReadParams(@Optional("true") String makeDistributionReadValue) { + makeDistributionValue = makeDistributionReadValue; + } + + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List") + public void onboardVNFShotFlow(String filepath, String vnfFile) throws Exception, Throwable { + setLog(vnfFile); + System.out.println("print - >" + makeDistributionValue); + runOnboardToDistributionFlow(filepath, vnfFile); + } + + + + + + public void runOnboardToDistributionFlow(String filepath, String vnfFile) throws Exception { + + ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile)); + User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + Pair createVendorSoftwareProduct = OnboardingUtillViaApis.createVspViaApis(filepath, vnfFile, user); + VendorSoftwareProductObject vendorSoftwareProductObject = createVendorSoftwareProduct.right; + vendorSoftwareProductObject.setVspName(createVendorSoftwareProduct.left); + + // create VF base on VNF imported from previous step - have, resourceReqDetails object include part of resource metadata + ResourceReqDetails resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(vendorSoftwareProductObject, vendorSoftwareProductObject.getVspName()); + ExtentTestActions.log(Status.INFO, String.format("Create VF %s From VSP", resourceReqDetails.getName())); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails, vendorSoftwareProductObject.getVspName()); + ExtentTestActions.log(Status.INFO, String.format("Certify VF")); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //--------------------------SERVICE-------------------------------- + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(user); + ExtentTestActions.log(Status.INFO, String.format("Create Service %s", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + ExtentTestActions.log(Status.INFO, String.format("add VF to Service")); + Either addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + addComponentInstanceToComponentContainer.left().value(); + ExtentTestActions.log(Status.INFO, String.format("Certify Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + ExtentTestActions.log(Status.INFO, String.format("Distribute Service")); + AtomicOperationUtils.distributeService(service, true); + + ExtentTestActions.log(Status.INFO, String.format("The onboarding %s test is passed ! ", vnfFile)); + } + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java index 18b2329663..d7ac4a5676 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaDefinition.java @@ -29,9 +29,7 @@ public class ToscaDefinition { String tosca_definitions_version; Map metadata; -// Map imports; -// TODO waiting for answer about imports representation - Object imports; + List> imports; Map node_types; ToscaTopologyTemplateDefinition topology_template; @@ -39,54 +37,49 @@ public class ToscaDefinition { super(); } - @Override - public String toString() { - return "ToscaDefinition [tosca_definitions_version=" + tosca_definitions_version + ", metadata=" + metadata + ", imports=" + imports + ", node_types=" + node_types + ", topology_template=" + topology_template + "]"; - } - public String getTosca_definitions_version() { - return tosca_definitions_version; - } - public void setTosca_definitions_version(String tosca_definitions_version) { + public ToscaDefinition(String tosca_definitions_version, Map metadata, List> imports, Map node_types, + ToscaTopologyTemplateDefinition topology_template) { + super(); this.tosca_definitions_version = tosca_definitions_version; + this.metadata = metadata; + this.imports = imports; + this.node_types = node_types; + this.topology_template = topology_template; } + + public Map getMetadata() { return metadata; } + + public void setMetadata(Map metadata) { this.metadata = metadata; } - - -// public Map getImports() { -// return (Map) imports; -// } -// -// public void setImports(Map imports) { -// this.imports = imports; -// } -// -// public List getImports() { -// return (List) imports; -// } -// -// public void setImports(List imports) { -// this.imports = imports; -// } - - public Object getImports() { + + public List> getImports() { return imports; } - public void setImports(Object imports) { + public void setImports(List> imports) { this.imports = imports; } + public String getTosca_definitions_version() { + return tosca_definitions_version; + } + + public void setTosca_definitions_version(String tosca_definitions_version) { + this.tosca_definitions_version = tosca_definitions_version; + } + + public Map getNode_types() { return node_types; } @@ -109,9 +102,7 @@ public class ToscaDefinition { public static TypeDescription getTypeDescription(){ TypeDescription typeDescription = new TypeDescription(ToscaDefinition.class); typeDescription.putMapPropertyType("metadata", String.class, String.class); -// TODO Andrey imports format - typeDescription.putMapPropertyType("imports", String.class, ToscaImportsDefinition.class); -// typeDescription.putListPropertyType("imports", List.class); + typeDescription.putListPropertyType("imports", Map.class); typeDescription.putMapPropertyType("node_types", String.class, ToscaNodeTypesDefinition.class); return typeDescription; } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsMetadataDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsMetadataDefinition.java deleted file mode 100644 index eec057ed52..0000000000 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsMetadataDefinition.java +++ /dev/null @@ -1,84 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.ci.tests.tosca.datatypes; - -public class ToscaGroupsMetadataDefinition { - - private String vfModuleModelName; - private String vfModuleModelInvariantUUID; - private String vfModuleModelCustomizationUUID; - private String vfModuleModelUUID; - private String vfModuleModelVersion; - - public ToscaGroupsMetadataDefinition() { - super(); - // TODO Auto-generated constructor stub - } - - public String getVfModuleModelName() { - return vfModuleModelName; - } - - public void setVfModuleModelName(String vfModuleModelName) { - this.vfModuleModelName = vfModuleModelName; - } - - public String getVfModuleModelInvariantUUID() { - return vfModuleModelInvariantUUID; - } - - public void setVfModuleModelInvariantUUID(String vfModuleModelInvariantUUID) { - this.vfModuleModelInvariantUUID = vfModuleModelInvariantUUID; - } - - public String getVfModuleModelCustomizationUUID() { - return vfModuleModelCustomizationUUID; - } - - public void setVfModuleModelCustomizationUUID(String vfModuleModelCustomizationUUID) { - this.vfModuleModelCustomizationUUID = vfModuleModelCustomizationUUID; - } - - public String getVfModuleModelUUID() { - return vfModuleModelUUID; - } - - public void setVfModuleModelUUID(String vfModuleModelUUID) { - this.vfModuleModelUUID = vfModuleModelUUID; - } - - public String getVfModuleModelVersion() { - return vfModuleModelVersion; - } - - public void setVfModuleModelVersion(String vfModuleModelVersion) { - this.vfModuleModelVersion = vfModuleModelVersion; - } - - @Override - public String toString() { - return "ToscaGroupsMetadataDefinition [vfModuleModelName=" + vfModuleModelName + ", vfModuleModelInvariantUUID=" + vfModuleModelInvariantUUID + ", vfModuleModelCustomizationUUID=" + vfModuleModelCustomizationUUID - + ", vfModuleModelUUID=" + vfModuleModelUUID + ", vfModuleModelVersion=" + vfModuleModelVersion + "]"; - } - - - -} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java index dc3c40751c..e3051515cd 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaGroupsTopologyTemplateDefinition.java @@ -35,17 +35,17 @@ public class ToscaGroupsTopologyTemplateDefinition { private Map interfaces; private List members; // private Map metadata; - private ToscaGroupsMetadataDefinition metadata; + private ToscaServiceGroupsMetadataDefinition metadata; public ToscaGroupsTopologyTemplateDefinition() { super(); } - public ToscaGroupsMetadataDefinition getMetadata() { + public ToscaServiceGroupsMetadataDefinition getMetadata() { return metadata; } - public void setMetadata(ToscaGroupsMetadataDefinition metadata) { + public void setMetadata(ToscaServiceGroupsMetadataDefinition metadata) { this.metadata = metadata; } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java index d62e33e1dd..a5070b8662 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaImportsDefinition.java @@ -20,8 +20,11 @@ package org.openecomp.sdc.ci.tests.tosca.datatypes; +import org.yaml.snakeyaml.TypeDescription; + public class ToscaImportsDefinition { + private String name; private String file; private String repository; private String namespace_uri; @@ -32,17 +35,21 @@ public class ToscaImportsDefinition { // TODO Auto-generated constructor stub } - public ToscaImportsDefinition(String file, String repository, String namespace_uri, String namespace_prefix) { + public ToscaImportsDefinition(String name, String file, String repository, String namespace_uri, String namespace_prefix) { super(); + this.name = name; this.file = file; this.repository = repository; this.namespace_uri = namespace_uri; this.namespace_prefix = namespace_prefix; } - @Override - public String toString() { - return "ToscaImportsDefinition [file=" + file + ", repository=" + repository + ", namespace_uri=" + namespace_uri + ", namespace_prefix=" + namespace_prefix + "]"; + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; } public String getFile() { @@ -76,6 +83,13 @@ public class ToscaImportsDefinition { public void setNamespace_prefix(String namespace_prefix) { this.namespace_prefix = namespace_prefix; } + + //gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaImportsDefinition.class); + return typeDescription; + } + } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java index 6f9590f0ae..45feadecca 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaInputsTopologyTemplateDefinition.java @@ -22,6 +22,8 @@ package org.openecomp.sdc.ci.tests.tosca.datatypes; import java.util.Map; +import org.yaml.snakeyaml.TypeDescription; + public class ToscaInputsTopologyTemplateDefinition { private Map> inputs; @@ -40,6 +42,10 @@ public class ToscaInputsTopologyTemplateDefinition { } - + //gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaInputsTopologyTemplateDefinition.class); + return typeDescription; + } } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaMetadataDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaMetadataDefinition.java new file mode 100644 index 0000000000..ceba7adbe4 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaMetadataDefinition.java @@ -0,0 +1,196 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.tosca.datatypes; + +import org.yaml.snakeyaml.TypeDescription; + +public class ToscaMetadataDefinition { + + private String invariantUUID; + private String UUID; + private String name; + private String description; + private String type; + private String category; + private String subcategory; + private String resourceVendor; + private String resourceVendorRelease; + private String resourceVendorModelNumber; + private String serviceType; + private String serviceRole; + private String serviceEcompNaming; + private String ecompGeneratedNaming; + private String namingPolicy; + + public ToscaMetadataDefinition(String invariantUUID, String uUID, String name, String description, String type, String category, String subcategory, String resourceVendor, String resourceVendorRelease, String resourceVendorModelNumber, + String serviceType, String serviceRole, String serviceEcompNaming, String ecompGeneratedNaming, String namingPolicy) { + super(); + this.invariantUUID = invariantUUID; + UUID = uUID; + this.name = name; + this.description = description; + this.type = type; + this.category = category; + this.subcategory = subcategory; + this.resourceVendor = resourceVendor; + this.resourceVendorRelease = resourceVendorRelease; + this.resourceVendorModelNumber = resourceVendorModelNumber; + this.serviceType = serviceType; + this.serviceRole = serviceRole; + this.serviceEcompNaming = serviceEcompNaming; + this.ecompGeneratedNaming = ecompGeneratedNaming; + this.namingPolicy = namingPolicy; + } + + public String getInvariantUUID() { + return invariantUUID; + } + + public void setInvariantUUID(String invariantUUID) { + this.invariantUUID = invariantUUID; + } + + public String getUUID() { + return UUID; + } + + public void setUUID(String uUID) { + UUID = uUID; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getCategory() { + return category; + } + + public void setCategory(String category) { + this.category = category; + } + + public String getSubcategory() { + return subcategory; + } + + public void setSubcategory(String subcategory) { + this.subcategory = subcategory; + } + + public String getResourceVendor() { + return resourceVendor; + } + + public void setResourceVendor(String resourceVendor) { + this.resourceVendor = resourceVendor; + } + + public String getResourceVendorRelease() { + return resourceVendorRelease; + } + + public void setResourceVendorRelease(String resourceVendorRelease) { + this.resourceVendorRelease = resourceVendorRelease; + } + + public String getResourceVendorModelNumber() { + return resourceVendorModelNumber; + } + + public void setResourceVendorModelNumber(String resourceVendorModelNumber) { + this.resourceVendorModelNumber = resourceVendorModelNumber; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceRole() { + return serviceRole; + } + + public void setServiceRole(String serviceRole) { + this.serviceRole = serviceRole; + } + + public String getServiceEcompNaming() { + return serviceEcompNaming; + } + + public void setServiceEcompNaming(String serviceEcompNaming) { + this.serviceEcompNaming = serviceEcompNaming; + } + + public String getEcompGeneratedNaming() { + return ecompGeneratedNaming; + } + + public void setEcompGeneratedNaming(String ecompGeneratedNaming) { + this.ecompGeneratedNaming = ecompGeneratedNaming; + } + + public String getNamingPolicy() { + return namingPolicy; + } + + public void setNamingPolicy(String namingPolicy) { + this.namingPolicy = namingPolicy; + } + + @Override + public String toString() { + return "ToscaMetadataDefinition [invariantUUID=" + invariantUUID + ", UUID=" + UUID + ", name=" + name + ", description=" + description + ", type=" + type + ", category=" + category + ", subcategory=" + subcategory + + ", resourceVendor=" + resourceVendor + ", resourceVendorRelease=" + resourceVendorRelease + ", resourceVendorModelNumber=" + resourceVendorModelNumber + ", serviceType=" + serviceType + ", serviceRole=" + serviceRole + + ", serviceEcompNaming=" + serviceEcompNaming + ", ecompGeneratedNaming=" + ecompGeneratedNaming + ", namingPolicy=" + namingPolicy + "]"; + } + + //gets Type description for Yaml snake + public static TypeDescription getTypeDescription(){ + TypeDescription typeDescription = new TypeDescription(ToscaMetadataDefinition.class); + return typeDescription; + } + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java new file mode 100644 index 0000000000..86ca8f56cf --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/datatypes/ToscaServiceGroupsMetadataDefinition.java @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.tosca.datatypes; + +public class ToscaServiceGroupsMetadataDefinition { + + private String vfModuleModelName; + private String vfModuleModelInvariantUUID; + private String vfModuleModelCustomizationUUID; + private String vfModuleModelUUID; + private String vfModuleModelVersion; + + public ToscaServiceGroupsMetadataDefinition() { + super(); + // TODO Auto-generated constructor stub + } + + public String getVfModuleModelName() { + return vfModuleModelName; + } + + public void setVfModuleModelName(String vfModuleModelName) { + this.vfModuleModelName = vfModuleModelName; + } + + public String getVfModuleModelInvariantUUID() { + return vfModuleModelInvariantUUID; + } + + public void setVfModuleModelInvariantUUID(String vfModuleModelInvariantUUID) { + this.vfModuleModelInvariantUUID = vfModuleModelInvariantUUID; + } + + public String getVfModuleModelCustomizationUUID() { + return vfModuleModelCustomizationUUID; + } + + public void setVfModuleModelCustomizationUUID(String vfModuleModelCustomizationUUID) { + this.vfModuleModelCustomizationUUID = vfModuleModelCustomizationUUID; + } + + public String getVfModuleModelUUID() { + return vfModuleModelUUID; + } + + public void setVfModuleModelUUID(String vfModuleModelUUID) { + this.vfModuleModelUUID = vfModuleModelUUID; + } + + public String getVfModuleModelVersion() { + return vfModuleModelVersion; + } + + public void setVfModuleModelVersion(String vfModuleModelVersion) { + this.vfModuleModelVersion = vfModuleModelVersion; + } + + @Override + public String toString() { + return "ToscaGroupsMetadataDefinition [vfModuleModelName=" + vfModuleModelName + ", vfModuleModelInvariantUUID=" + vfModuleModelInvariantUUID + ", vfModuleModelCustomizationUUID=" + vfModuleModelCustomizationUUID + + ", vfModuleModelUUID=" + vfModuleModelUUID + ", vfModuleModelVersion=" + vfModuleModelVersion + "]"; + } + + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/model/ToscaMetadataFieldsPresentationEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/model/ToscaMetadataFieldsPresentationEnum.java new file mode 100644 index 0000000000..cdea2ff69c --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/tosca/model/ToscaMetadataFieldsPresentationEnum.java @@ -0,0 +1,74 @@ +package org.openecomp.sdc.ci.tests.tosca.model; + +public class ToscaMetadataFieldsPresentationEnum { + + public enum ToscaMetadataFieldsEnum { +// general + INVARIANT_UUID ("invariantUUID", ComponentTypeEnum.RESOURCE_SERVICE_NODE_TEMPLATE.value), + UUID ("UUID", ComponentTypeEnum.RESOURCE_SERVICE_NODE_TEMPLATE.value), + NAME ("name", ComponentTypeEnum.RESOURCE_SERVICE_NODE_TEMPLATE.value), + DESCRIPTION ("description", ComponentTypeEnum.RESOURCE_SERVICE_NODE_TEMPLATE.value), + CATEGORY ("category", ComponentTypeEnum.RESOURCE_SERVICE_NODE_TEMPLATE.value), + TYPE ("type", ComponentTypeEnum.RESOURCE_SERVICE_NODE_TEMPLATE.value), + +// resource + SUBCATEGORY ("subcategory", ComponentTypeEnum.RESOURCE_NODE_TEMPLATE.value), + RESOURCE_VENDOR_NAME ("resourceVendor", ComponentTypeEnum.RESOURCE_NODE_TEMPLATE.value), + RESOURCE_VENDOR_RELEASE ("resourceVendorRelease", ComponentTypeEnum.RESOURCE_NODE_TEMPLATE.value), + RESOURCE_VENDOR_MODEL_NUMBER ("resourceVendorModelNumber", ComponentTypeEnum.RESOURCE_NODE_TEMPLATE.value), + +// service + SERVICE_TYPE ("serviceType", ComponentTypeEnum.SERVICE.value), + SERVICE_ROLE ("serviceRole", ComponentTypeEnum.SERVICE.value), + SERVICE_ECOMP_NAMING ("serviceEcompNaming", ComponentTypeEnum.SERVICE.value), + ECOMP_GENERATED_NAMING ("ecompGeneratedNaming", ComponentTypeEnum.SERVICE.value), + NAMING_POLICY ("namingPolicy", ComponentTypeEnum.SERVICE.value), + +// node_template + CUSTOMIZATION_UUID ("customizationUUID", ComponentTypeEnum.NODE_TEMPLATE.value), + VERSION ("version", ComponentTypeEnum.RESOURCE_GROUP_NODE_TEMPLATE.value), + +// service group: + VF_MODULE_MODEL_NAME ("vfModuleModelName", ComponentTypeEnum.RESOURCE_GROUP_SERVICE_GROUP.value), + VF_MODULE_MODEL_INVARIANT_UUID ("vfModuleModelInvariantUUID", ComponentTypeEnum.RESOURCE_GROUP_SERVICE_GROUP.value), + VF_MODULE_MODEL_UUID ("vfModuleModelUUID", ComponentTypeEnum.RESOURCE_GROUP_SERVICE_GROUP.value), + VF_MODULE_MODEL_VERSION ("vfModuleModelVersion", ComponentTypeEnum.RESOURCE_GROUP_SERVICE_GROUP.value), + + VF_MODULE_MODEL_CUSTOMIZATION_UUID ("vfModuleModelCustomizationUUID", ComponentTypeEnum.SERVICE_GROUP.value) + ; + + + + public String value; + public String componentTypes; + + private ToscaMetadataFieldsEnum(String value, String componentTypes) { + this.value = value; + this.componentTypes = componentTypes; + } + + } + + + public enum ComponentTypeEnum { +// RESOURCE_SERVICE_NODE_TEMPLATE_RESOURCE_GROUP("resource, service, nodeTemplate, resourceGroup"), + RESOURCE_SERVICE_NODE_TEMPLATE("resource, service, nodeTemplate"), + RESOURCE_NODE_TEMPLATE("resource, nodeTemplate"), + SERVICE("service"), + NODE_TEMPLATE("nodeTemplate"), + RESOURCE_GROUP_NODE_TEMPLATE("resourceGroup, nodeTemplate"), + SERVICE_GROUP("serviceGroup"), + RESOURCE_GROUP_SERVICE_GROUP("resourceGroup, serviceGroup"), + + ; + + private String value; + + private ComponentTypeEnum(String value) { + this.value = value; + } + + } + + +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java index 3bae41fc57..5926798ceb 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/ToscaParserUtils.java @@ -29,12 +29,13 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; -import java.util.Set; -import org.openecomp.sdc.ci.tests.datatypes.enums.ToscaKeysEnum; import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaDefinition; import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaImportsDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaInputsTopologyTemplateDefinition; +import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaMetadataDefinition; import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaNodeTemplatesTopologyTemplateDefinition; import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaParameterConstants; import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaSubstitutionMappingsDefinition; @@ -42,12 +43,10 @@ import org.openecomp.sdc.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinitio import org.openecomp.sdc.ci.tests.utils.general.ElementFactory; import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; import org.openecomp.sdc.ci.tests.utils.rest.ImportRestUtils; -import org.openecomp.sdc.ci.tests.utils.validation.CsarValidationUtils; import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray; import org.openecomp.sdc.common.util.ZipUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; import org.yaml.snakeyaml.introspector.PropertyUtils; @@ -158,7 +157,9 @@ public class ToscaParserUtils { toscaStructure.addTypeDescription(ToscaNodeTemplatesTopologyTemplateDefinition.getTypeDescription()); toscaStructure.addTypeDescription(ToscaGroupsTopologyTemplateDefinition.getTypeDescription()); toscaStructure.addTypeDescription(ToscaSubstitutionMappingsDefinition.getTypeDescription()); - + toscaStructure.addTypeDescription(ToscaImportsDefinition.getTypeDescription()); + toscaStructure.addTypeDescription(ToscaMetadataDefinition.getTypeDescription()); + toscaStructure.addTypeDescription(ToscaInputsTopologyTemplateDefinition.getTypeDescription()); // Skip properties which are found in YAML, but not found in POJO PropertyUtils propertyUtils = new PropertyUtils(); propertyUtils.setSkipMissingProperties(true); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java index 17148ce8a9..58ab9f353e 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/AtomicOperationUtils.java @@ -39,6 +39,7 @@ import org.apache.commons.lang3.tuple.Pair; import org.aspectj.apache.bcel.classfile.Code; import org.json.JSONException; import org.openecomp.sdc.be.datatypes.elements.ConsumerDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; import org.openecomp.sdc.be.model.ArtifactDefinition; import org.openecomp.sdc.be.model.Component; @@ -50,6 +51,7 @@ import org.openecomp.sdc.be.model.Resource; import org.openecomp.sdc.be.model.Service; import org.openecomp.sdc.be.model.User; import org.openecomp.sdc.ci.tests.api.Urls; +import org.openecomp.sdc.ci.tests.config.Config; import org.openecomp.sdc.ci.tests.datatypes.ArtifactReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ComponentInstanceReqDetails; import org.openecomp.sdc.ci.tests.datatypes.ImportReqDetails; @@ -67,6 +69,7 @@ import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum; import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.utils.Utils; import org.openecomp.sdc.ci.tests.utils.rest.ArtifactRestUtils; import org.openecomp.sdc.ci.tests.utils.rest.BaseRestUtils; import org.openecomp.sdc.ci.tests.utils.rest.ComponentInstanceRestUtils; @@ -134,6 +137,25 @@ public final class AtomicOperationUtils { } } + public static Either createResourceByResourceDetails(ResourceReqDetails resourceDetails, UserRoleEnum userRole, Boolean validateState) { + try { + User defaultUser = ElementFactory.getDefaultUser(userRole); + RestResponse resourceResp = ResourceRestUtils.createResource(resourceDetails, defaultUser); + + if (validateState) { + assertTrue(resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED); + } + + if (resourceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Resource resourceResponseObject = ResponseParser.convertResourceResponseToJavaObject(resourceResp.getResponse()); + return Either.left(resourceResponseObject); + } + return Either.right(resourceResp); + } catch (Exception e) { + throw new AtomicOperationException(e); + } + } + public static Either createResourcesByTypeNormTypeAndCatregory(ResourceTypeEnum resourceType, NormativeTypesEnum normativeTypes, ResourceCategoryEnum resourceCategory, UserRoleEnum userRole, Boolean validateState) throws Exception { User defaultUser = ElementFactory.getDefaultUser(userRole); @@ -206,6 +228,20 @@ public final class AtomicOperationUtils { return Either.right(createServiceResp); } + public static Either createCustomService(ServiceReqDetails serviceDetails, UserRoleEnum userRole, Boolean validateState) throws Exception { + User defaultUser = ElementFactory.getDefaultUser(userRole); + RestResponse createServiceResp = ServiceRestUtils.createService(serviceDetails, defaultUser); + + if (validateState) { + assertTrue(createServiceResp.getErrorCode() == ServiceRestUtils.STATUS_CODE_CREATED); + } + + if (createServiceResp.getErrorCode() == ResourceRestUtils.STATUS_CODE_CREATED) { + Service serviceResponseObject = ResponseParser.convertServiceResponseToJavaObject(createServiceResp.getResponse()); + return Either.left(serviceResponseObject); + } + return Either.right(createServiceResp); + } // *********** PRODUCT **************** public static Either createDefaultProduct(UserRoleEnum userRole, Boolean validateState) throws Exception { @@ -713,16 +749,21 @@ public final class AtomicOperationUtils { } } - public static Either getServiceToscaArtifactPayload(Service service, String artifactType) throws Exception { + public static Either getComponenetArtifactPayload(Component component, String artifactType) throws Exception { - String url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, "localhost", "8080", service.getUniqueId(), service.getToscaArtifacts().get(artifactType).getUniqueId()); - String userId = service.getLastUpdaterUserId(); + String url; + Config config = Utils.getConfig(); + if(component.getComponentType().toString().toUpperCase().equals(ComponentTypeEnum.SERVICE.getValue().toUpperCase())){ + url = String.format(Urls.UI_DOWNLOAD_SERVICE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), component.getToscaArtifacts().get(artifactType).getUniqueId()); + }else{ + url = String.format(Urls.UI_DOWNLOAD_RESOURCE_ARTIFACT, config.getCatalogBeHost(), config.getCatalogBePort(), component.getUniqueId(), component.getToscaArtifacts().get(artifactType).getUniqueId()); + } + String userId = component.getLastUpdaterUserId(); Map headersMap = new HashMap(); headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); headersMap.put(HttpHeaderEnum.CACHE_CONTROL.getValue(), "no-cache"); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), basicAuthentication); headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); -// headersMap.put("X-ECOMP-InstanceID", "test"); if (userId != null) { headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); } @@ -735,4 +776,6 @@ public final class AtomicOperationUtils { } + + } diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java index 5c23b5f3fe..ddca429f2c 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/ElementFactory.java @@ -293,7 +293,7 @@ public class ElementFactory { tags.add("serviceTag1"); tags.add(serviceName); String description = "service Description"; - String icon = "myIcon"; + String icon = "defaulticon"; ServiceReqDetails serviceDetails = new ServiceReqDetails(serviceName, category.getValue(), tags, description, contactId, icon); @@ -979,7 +979,7 @@ public class ElementFactory { return requirementDef; } - private static String generateUUIDforSufix() { + public static String generateUUIDforSufix() { String uniqueSufix = UUID.randomUUID().toString(); String[] split = uniqueSufix.split("-"); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java new file mode 100644 index 0000000000..77be6df729 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/FileHandling.java @@ -0,0 +1,542 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.general; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import org.apache.commons.io.FileUtils; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.config.Config; + +import org.openecomp.sdc.common.util.GeneralUtility; +import org.yaml.snakeyaml.Yaml; + +import java.io.*; +import java.nio.file.Paths; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipException; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +import static org.testng.AssertJUnit.assertTrue; + +public class FileHandling { + +// ------------------yaml parser methods---------------------------- + public static Map parseYamlFile(String filePath) throws Exception { + Yaml yaml = new Yaml(); + File file = new File(filePath); + InputStream inputStream = new FileInputStream(file); + Map map = (Map) yaml.load(inputStream); + return map; + } + + /** + * The method return map fetched objects by pattern from yaml file + * @param yamlFile + * @param pattern + * @return + * @throws Exception + */ + public static Map parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception { + Map yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString()); + Map objectMap = getObjectMapByPattern(yamlFileToMap, pattern); + return objectMap; + } + + @SuppressWarnings("unchecked") + public static Map getObjectMapByPattern(Map parseUpdetedEnvFile, String pattern) { + Map objectMap = null; + + Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern); + if(objectUpdetedEnvFile instanceof HashMap){ + objectMap = (Map) objectUpdetedEnvFile; + } + return objectMap; + } + + + public static Map parseDataTypesYaml(String filePath) throws Exception { + @SuppressWarnings("unchecked") + Map dataTypesMap = (Map) parseYamlFile(filePath); + return dataTypesMap; + } +// ------------------------------------------------------------------------------------------------- + + public static String getFilePath(String folder) { + String filepath = System.getProperty("filepath"); + if (filepath == null && System.getProperty("os.name").contains("Windows")) { + filepath = FileHandling.getResourcesFilesPath() + folder + File.separator; + } + + else if(filepath.isEmpty() && !System.getProperty("os.name").contains("Windows")){ + filepath = FileHandling.getBasePath() + "Files" + File.separator + folder + File.separator; + } + + System.out.println(filepath); + + return filepath; + } + + public static String getBasePath() { + return System.getProperty("user.dir") + File.separator; + } + + public static String getSdcVnfsPath() { + return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString(); + } + + public static String getDriversPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci" + File.separator + "drivers" + File.separator; + } + + public static String getResourcesFilesPath() { +// return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" +// + File.separator + "Files" + File.separator; + + return getSdcVnfsPath()+ File.separator + "ui-tests" + File.separator + "Files" + File.separator; + } + + public static String getResourcesEnvFilesPath() { + return getBasePath() + File.separator + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "Files" + File.separator + "ResourcesEnvFiles" +File.separator; + } + + public static String getCiFilesPath() { + return getBasePath() + "src" + File.separator + "main" + File.separator + "resources" + + File.separator + "ci"; + } + + public static String getConfFilesPath() { + return getCiFilesPath() + File.separator + "conf" + File.separator; + } + + public static String getTestSuitesFilesPath() { + return getCiFilesPath() + File.separator + "testSuites" + File.separator; + } + + public static String getVnfRepositoryPath() { + return getFilePath("VNFs"); + } + + public static File getConfigFile(String configFileName) throws Exception { + File configFile = new File(FileHandling.getBasePath() + File.separator + "conf" + File.separator + configFileName); + if (!configFile.exists()) { + configFile = new File(FileHandling.getConfFilesPath() + configFileName); + } + return configFile; + } + + public static Object[] filterFileNamesFromFolder(String filepath, String extension) { + try { + File dir = new File(filepath); + List filenames = new ArrayList(); + + FilenameFilter extensionFilter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(extension); + } + }; + + if (dir.isDirectory()) { + for (File file : dir.listFiles(extensionFilter)) { + filenames.add(file.getName()); + } + return filenames.toArray(); + } + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static List filterFileNamesListFromFolder(String filepath, String extension) { + try { + File dir = new File(filepath); + List filenames = new ArrayList(); + + FilenameFilter extensionFilter = new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.endsWith(extension); + } + }; + + if (dir.isDirectory()) { + for (File file : dir.listFiles(extensionFilter)) { + filenames.add(file.getName()); + } + return filenames; + } + + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + public static String[] getArtifactsFromZip(String filepath, String zipFilename){ + try{ + ZipFile zipFile = new ZipFile(filepath + File.separator + zipFilename); + Enumeration entries = zipFile.entries(); + + String[] artifactNames = new String[zipFile.size() - 1]; + + int i = 0; + while(entries.hasMoreElements()){ + ZipEntry nextElement = entries.nextElement(); + if (!nextElement.isDirectory()){ + if (!nextElement.getName().equals("MANIFEST.json")){ + String name = nextElement.getName(); + artifactNames[i++] = name; + } + } + } + zipFile.close(); + return artifactNames; + } + catch(ZipException zipEx){ + System.err.println("Error in zip file named : " + zipFilename); + zipEx.printStackTrace(); + } catch (IOException e) { + System.err.println("Unhandled exception : "); + e.printStackTrace(); + } + + return null; + + } + +// public static Object[] getZipFileNamesFromFolder(String filepath) { +// return filterFileNamesFromFolder(filepath, ".zip"); +// } + + public static List getZipFileNamesFromFolder(String filepath) { + return filterFileNamesListFromFolder(filepath, ".zip"); + } + + public static int countFilesInZipFile(String[] artifactsArr, String reqExtension){ + int fileCounter = 0; + for (String artifact : artifactsArr){ + String extensionFile = artifact.substring(artifact.lastIndexOf(".") + 1 , artifact.length()); + if (extensionFile.equals(reqExtension)){ + fileCounter++; + } + } + return fileCounter; + } + + + /** + * @return last modified file name from default directory + * @throws Exception + */ +// TODO add download directory capability +// public static synchronized File getLastModifiedFileNameFromDir() throws Exception{ +// return getLastModifiedFileNameFromDir(ComponentBaseTest.getWindowTest().getDownloadDirectory()); +// } + + /** + * @param dirPath + * @return last modified file name from dirPath directory + */ + public static synchronized File getLastModifiedFileNameFromDir(String dirPath){ + File dir = new File(dirPath); + File[] files = dir.listFiles(); + if (files == null) { + assertTrue("File not found under directory " + dirPath, false); + return null; + } + + File lastModifiedFile = files[0]; + for (int i = 1; i < files.length; i++) { + if(files[i].isDirectory()) { + continue; + } + if (lastModifiedFile.lastModified() < files[i].lastModified()) { + lastModifiedFile = files[i]; + } + } + return lastModifiedFile; + } + + public static void deleteDirectory(String directoryPath) { + File dir = new File(directoryPath); + try { + FileUtils.deleteDirectory(dir); + } catch (IOException e) { + System.out.println("Failed to delete " + dir); + ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to delete " + dir); + } + } + + public static void createDirectory(String directoryPath) { + File directory = new File(String.valueOf(directoryPath)); + if (! directory.exists()){ + directory.mkdir(); + } + } + + + /** + * The method append data to existing file, if file not exists - create it + * @param pathToFile + * @param text + * @param leftSpaceCount + * @throws IOException + */ + public static synchronized void writeToFile(File pathToFile, Object text, Integer leftSpaceCount) throws IOException{ + + BufferedWriter bw = null; + FileWriter fw = null; + if(!pathToFile.exists()){ + createEmptyFile(pathToFile); + } + try { + fw = new FileWriter(pathToFile, true); + bw = new BufferedWriter(fw); + StringBuilder sb = new StringBuilder(); + if(leftSpaceCount > 0 ){ + for(int i = 0; i < leftSpaceCount; i++){ + sb.append(" "); + } + } + bw.write(sb.toString() + text); + bw.newLine(); + bw.close(); + fw.close(); + } catch (Exception e) { + ComponentBaseTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + +// public static synchronized void writeToFile(File pathToFile, Map> dataMap, Integer leftSpaceCount) throws IOException{ +// +// BufferedWriter bw = null; +// FileWriter fw = null; +// try { +// if(!pathToFile.exists()){ +// createEmptyFile(pathToFile); +// } +// fw = new FileWriter(pathToFile, true); +// bw = new BufferedWriter(fw); +// StringBuilder sb = new StringBuilder(); +// if(leftSpaceCount > 0 ){ +// for(int i = 0; i < leftSpaceCount; i++){ +// sb.append(" "); +// } +// } +// for(Map.Entry> entry : dataMap.entrySet()){ +// Object record = ArtifactUIUtils.getFormatedData(entry.getKey(), entry.getValue().right); +// bw.write(sb.toString() + record); +// bw.newLine(); +// } +// bw.close(); +// fw.close(); +// } catch (Exception e) { +// ComponentBaseTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); +// } +// } + + public static void deleteLastDowloadedFiles(List files) throws IOException { + for (File file : files) { + File fileToDelete =new File(Config.instance().getWindowsDownloadDirectory()+file.getName()); + fileToDelete.delete(); + } + } +// TODO add work with directory capaability +// public static void cleanCurrentDownloadDir() throws IOException { +// try{ +// ExtentTestActions.log(Status.INFO, "Cleaning directory " + ComponentBaseTest.getWindowTest().getDownloadDirectory()); +// System.gc(); +// FileUtils.cleanDirectory(new File(ComponentBaseTest.getWindowTest().getDownloadDirectory())); +// } +// catch(Exception e){ +// +// } +// } + + public static boolean isFileDownloaded(String downloadPath, String fileName) { + boolean flag = false; + File dir = new File(downloadPath); + File[] dir_contents = dir.listFiles(); + for (int i = 0; i < dir_contents.length; i++) { + if (dir_contents[i].getName().equals(fileName)) + return flag = true; + } + return flag; + } + + public static String getMD5OfFile(File file) throws IOException { + String content = FileUtils.readFileToString(file); + String md5 = GeneralUtility.calculateMD5Base64EncodedByString(content); + return md5; + } + + public static File createEmptyFile(String fileToCreate) { + File file= new File(fileToCreate); + try { + if(file.exists()){ + deleteFile(file); + } + file.createNewFile(); + ComponentBaseTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return file; + } + + public static File createEmptyFile(File fileToCreate) { + try { + if(fileToCreate.exists()){ + deleteFile(fileToCreate); + } + fileToCreate.createNewFile(); + ComponentBaseTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to create file " + fileToCreate); + e.printStackTrace(); + } + return fileToCreate; + } + + public static void deleteFile(File file){ + + try{ + if(file.exists()){ + file.deleteOnExit(); + ComponentBaseTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted"); + }else{ + ComponentBaseTest.getExtendTest().log(Status.INFO, "Failed to delete file " + file.getName()); + } + }catch(Exception e){ + e.printStackTrace(); + } + + } + + + /** + * get file list from directory by extension array + * @param directory + * @param okFileExtensions + * @return + */ + public static List getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions){ + + List fileList = new ArrayList<>(); + File[] files = directory.listFiles(); + + for (String extension : okFileExtensions){ + for(File file : files){ + if (file.getName().toLowerCase().endsWith(extension)){ + fileList.add(file); + } + } + } + return fileList; + } + + private static final int BUFFER_SIZE = 4096; +// public static void unzip(String zipFilePath, String destDirectory) throws IOException { +// File destDir = new File(destDirectory); +// if (!destDir.exists()) { +// destDir.mkdir(); +// } +// ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath)); +// ZipEntry entry = zipIn.getNextEntry(); +//// iterates over entries in the zip file +// while (entry != null) { +// String entryName; +// if(System.getProperty("os.name").contains("Windows")){ +// entryName = entry.getName().replaceAll("/", "\\"+File.separator); +// }else{ +// entryName = entry.getName(); +// } +// String filePath = destDirectory + entryName; +// String currPath = destDirectory; +// String[] dirs = entryName.split("\\"+File.separator); +// String currToken; +// for(int i = 0; i prepareHeadersMap(String userId) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + return headersMap; + } + + public static Pair createVspViaApis(String filepath, String vnfFile, User user) throws Exception { + + VendorSoftwareProductObject vendorSoftwareProductObject = new VendorSoftwareProductObject(); + ExtentTestActions.log(Status.INFO, String.format("Create Vendor License")); + AmdocsLicenseMembers amdocsLicenseMembers = OnboardingUtils.createVendorLicense(user); + ExtentTestActions.log(Status.INFO, String.format("Create Vendor Software Product")); + Pair> createVendorSoftwareProduct = OnboardingUtils.createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers); + Map map = createVendorSoftwareProduct.right; + vendorSoftwareProductObject.setAttContact(map.get("attContact")); + vendorSoftwareProductObject.setCategory(map.get("category")); + vendorSoftwareProductObject.setComponentId(map.get("componentId")); + vendorSoftwareProductObject.setDescription(map.get("description")); + vendorSoftwareProductObject.setSubCategory(map.get("subCategory")); + vendorSoftwareProductObject.setVendorName(map.get("vendorName")); + vendorSoftwareProductObject.setVspId(map.get("vspId")); + Pair pair = new Pair(createVendorSoftwareProduct.left, vendorSoftwareProductObject); + return pair; + } + +/* public static Resource createResourceFromVSP(Pair> createVendorSoftwareProduct, String vspName) throws Exception { + List tags = new ArrayList<>(); + tags.add(vspName); + Map map = createVendorSoftwareProduct.right; + ResourceReqDetails resourceDetails = new ResourceReqDetails(); + resourceDetails.setCsarUUID(map.get("vspId")); + resourceDetails.setCsarVersion("1.0"); + resourceDetails.setName(vspName); + resourceDetails.setTags(tags); + resourceDetails.setDescription(map.get("description")); + resourceDetails.setResourceType(map.get("componentType")); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); + resourceDetails.setVendorName(map.get("vendorName")); + resourceDetails.setVendorRelease("1.0"); + resourceDetails.setResourceType("VF"); + resourceDetails.setResourceVendorModelNumber("666"); + resourceDetails.setContactId(map.get("attContact")); + resourceDetails.setIcon("defaulticon"); + Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value(); + + return resource; + }*/ + public static Resource createResourceFromVSP(ResourceReqDetails resourceDetails, String vspName) throws Exception { +// List tags = new ArrayList<>(); +// tags.add(vspName); +// Map map = createVendorSoftwareProduct.right; +// ResourceReqDetails resourceDetails = new ResourceReqDetails(); +// resourceDetails.setCsarUUID(map.get("vspId")); +// resourceDetails.setCsarVersion("1.0"); +// resourceDetails.setName(vspName); +// resourceDetails.setTags(tags); +// resourceDetails.setDescription(map.get("description")); +// resourceDetails.setResourceType(map.get("componentType")); +// resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); +// resourceDetails.setVendorName(map.get("vendorName")); +// resourceDetails.setVendorRelease("1.0"); +// resourceDetails.setResourceType("VF"); +// resourceDetails.setResourceVendorModelNumber("666"); +// resourceDetails.setContactId(map.get("attContact")); +// resourceDetails.setIcon("defaulticon"); + Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceDetails, UserRoleEnum.DESIGNER, true).left().value(); + + return resource; + } + public static void downloadToscaCsarToDirectory(Component component, File file) { + try { + Either componentToscaArtifactPayload = AtomicOperationUtils.getComponenetArtifactPayload(component, "assettoscacsar"); + if(componentToscaArtifactPayload.left().value() != null){ + convertPayloadToFile(componentToscaArtifactPayload.left().value(), file); + } + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +// public static void convertPayloadToFile(String payload, File file, boolean isBased64, boolean isSdcFormat) throws IOException{ +// +// Gson gson = new Gson(); +// byte[] byteArray = null; +// Map fromJson; +// @SuppressWarnings("unchecked") +// String string = null;// = fromJson.get("base64Contents").toString(); +// if(isSdcFormat){ +// fromJson = gson.fromJson(payload, Map.class); +// string = fromJson.get("base64Contents").toString(); +// }else if (isBased64) { +// byteArray = Base64.decode(string.getBytes(StandardCharsets.UTF_8)); +// }else{ +// byteArray = payload.getBytes(StandardCharsets.UTF_8); +// } +// File downloadedFile = new File(file.getAbsolutePath()); +// FileOutputStream fos = new FileOutputStream(downloadedFile); +// fos.write(byteArray); +// fos.flush(); +// fos.close(); +// +// } + + public static void convertPayloadToFile(String payload, File file) throws IOException{ + + Gson gson = new Gson(); + @SuppressWarnings("unchecked") + Map fromJson = gson.fromJson(payload, Map.class); + String string = fromJson.get("base64Contents").toString(); + byte[] byteArray = Base64.decodeBase64(string.getBytes(StandardCharsets.UTF_8)); + File downloadedFile = new File(file.getAbsolutePath()); + FileOutputStream fos = new FileOutputStream(downloadedFile); + fos.write(byteArray); + fos.flush(); + fos.close(); + } + + + public static void convertPayloadToZipFile(String payload, File file) throws IOException{ + + byte[] byteArray = payload.getBytes(StandardCharsets.ISO_8859_1); + File downloadedFile = new File(file.getAbsolutePath()); + FileOutputStream fos = new FileOutputStream(downloadedFile); + fos.write(byteArray); + fos.flush(); + fos.close(); + + +// ZipOutputStream fos = null; +// +// +// for (Charset charset : Charset.availableCharsets().values()) { +// try{ +// // System.out.println("How to do it???"); +// File downloadedFile = new File(file.getAbsolutePath() + "_" + charset +".csar"); +// fos = new ZipOutputStream(new FileOutputStream(downloadedFile)); +// byte[] byteArray = payload.getBytes(charset); +// fos.write(byteArray); +// fos.flush(); +// +// } +// catch(Exception e){ +// fos.close(); +// } +// } + System.out.println(""); + +// ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(byteArray)); +// ZipEntry entry = null; +// while ((entry = zipStream.getNextEntry()) != null) { +// +// String entryName = entry.getName(); +// +// FileOutputStream out = new FileOutputStream(file+"/"+entryName); +// +// byte[] byteBuff = new byte[4096]; +// int bytesRead = 0; +// while ((bytesRead = zipStream.read(byteBuff)) != -1) +// { +// out.write(byteBuff, 0, bytesRead); +// } +// +// out.close(); +// zipStream.closeEntry(); +// } +// zipStream.close(); +// + + + + BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(payload.getBytes(StandardCharsets.ISO_8859_1))); + String filePath = file.toString(); + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(filePath))); + int inByte; + while((inByte = bis.read()) != -1) bos.write(inByte); + bis.close(); + bos.close(); + } + + public static Either getVendorSoftwareProduct(String vspId, User user, Boolean validateState) throws Exception { + + Config config = Utils.getConfig(); + String url = String.format(Urls.GET_VENDOR_SOFTWARE_PRODUCT, config.getCatalogBeHost(), config.getCatalogBePort(), vspId); + String userId = user.getUserId(); + Map headersMap = prepareHeadersMap(userId); + headersMap.put(HttpHeaderEnum.X_ECOMP_REQUEST_ID_HEADER.getValue(), "123456"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "*/*"); + headersMap.put("Accept-Encoding", "gzip, deflate, br"); + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + if (validateState) { + assertTrue("add property to resource failed: " + response.getResponseMessage(), response.getErrorCode() == BaseRestUtils.STATUS_CODE_SUCCESS); + } + if (response.getErrorCode() != BaseRestUtils.STATUS_CODE_SUCCESS && response.getResponse().getBytes() == null && response.getResponse().getBytes().length == 0) { + return Either.right(response); + } + return Either.left(response.getResponse()); + + } + + public static ResourceReqDetails prepareOnboardedResourceDetailsBeforeCreate(VendorSoftwareProductObject vendorSoftwareProductObject, String vspName) { + + List tags = new ArrayList<>(); + tags.add(vspName); + ResourceReqDetails resourceDetails = new ResourceReqDetails(); + resourceDetails.setCsarUUID(vendorSoftwareProductObject.getVspId()); + resourceDetails.setCsarVersion("1.0"); + resourceDetails.setName(vspName); + resourceDetails.setTags(tags); + resourceDetails.setDescription(vendorSoftwareProductObject.getDescription()); + resourceDetails.addCategoryChain(ResourceCategoryEnum.GENERIC_DATABASE.getCategory(), ResourceCategoryEnum.GENERIC_DATABASE.getSubCategory()); + resourceDetails.setVendorName(vendorSoftwareProductObject.getVendorName()); + resourceDetails.setVendorRelease("1.0"); + resourceDetails.setResourceType("VF"); + resourceDetails.setResourceVendorModelNumber("666"); + resourceDetails.setContactId(vendorSoftwareProductObject.getAttContact()); + resourceDetails.setIcon("defaulticon"); + + return resourceDetails; + } + + public static ServiceReqDetails prepareServiceDetailsBeforeCreate(User user) { + + ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(ServiceCategoriesEnum.NETWORK_L4, user); + serviceDetails.setServiceType("MyServiceType"); + serviceDetails.setServiceRole("MyServiceRole"); + serviceDetails.setNamingPolicy("MyServiceNamingPolicy"); + serviceDetails.setEcompGeneratedNaming(false); + + return serviceDetails; + } +} diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java new file mode 100644 index 0000000000..a1838b66d1 --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/OnboardingUtils.java @@ -0,0 +1,799 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.general; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.simple.JSONArray; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.api.ComponentBaseTest; +import org.openecomp.sdc.ci.tests.api.ExtentTestActions; +import org.openecomp.sdc.ci.tests.config.Config; + +import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers; +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; + +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; + +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +import org.testng.Assert; + +import java.io.*; +import java.nio.file.FileSystems; +import java.util.*; +import java.util.stream.Collectors; + +import static org.testng.AssertJUnit.assertEquals; + +public class OnboardingUtils { + + protected static List exludeVnfList = Arrays.asList("2016-197_vscp_vscp-fw_1610_e2e.zip", "2016-281_vProbes_BE_11_1_f_30_1610_e2e.zip", + "2016-282_vProbes_FE_11_1_f_30_1610_e2e.zip", "2016-044_vfw_fnat_30_1607_e2e.zip", "2017-376_vMOG_11_1.zip", "vMOG.zip", + + + "vMRF_USP_AIC3.0_1702.zip", "2016-211_vprobesbe_vprobes_be_30_1610_e2e.zip", "2016-005_vprobesfe_vprobes_fe_30_1607_e2e.zip", + "vMRF_RTT.zip", "2016-006_vvm_vvm_30_1607_e2e.zip", "2016-001_vvm_vvm_30_1607_e2e.zip"); + + protected static List exludeVnfListForToscaParser = Arrays.asList("2016-043_vsaegw_fdnt_30_1607_e2e.zip", "vIRC_CC.zip", + "2016-045_vlb_lmsp_30_1607_e2e.zip", "2016-050_vdns_vmdns_30_1607_e2e.zip", + "2016-247_mns_mns_30_1610_e2e.zip", "2016-044_vfw_fcgi_30_1607_e2e.zip"); + + public OnboardingUtils() { + } + + public static Pair> createVendorSoftwareProduct(String HeatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) + throws Exception { + Pair> pair = createVSP(HeatFileName, filepath, user, amdocsLicenseMembers); + + String vspid = pair.right.get("vspId"); + + prepareVspForUse(user, vspid); + + return pair; + } + + public static void prepareVspForUse(User user, String vspid) throws Exception { + RestResponse checkin = checkinVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to checking new VSP", 200, checkin.getErrorCode().intValue()); + + RestResponse submit = submitVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to submit new VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspid, user); + assertEquals("did not succeed to create package of new VSP ", 200, createPackage.getErrorCode().intValue()); + + ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor software product"); + } + + public static Pair> createVSP(String HeatFileName, String filepath, User user, AmdocsLicenseMembers amdocsLicenseMembers) throws Exception { + String vspName = handleFilename(HeatFileName); + + ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor software product"); + + Pair> createNewVspPair = createNewVendorSoftwareProduct(vspName, amdocsLicenseMembers, user); + RestResponse createNewVendorSoftwareProduct = createNewVspPair.left; + assertEquals("did not succeed to create new VSP", 200,createNewVendorSoftwareProduct.getErrorCode().intValue()); + String vspid = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "vspId"); + String componentId = ResponseParser.getValueFromJsonResponse(createNewVendorSoftwareProduct.getResponse(), "componentId"); + + Map vspMeta = createNewVspPair.right; + Map vspObject = new HashMap(); + Iterator iterator = vspMeta.keySet().iterator(); + while(iterator.hasNext()){ + Object key = iterator.next(); + Object value = vspMeta.get(key); + vspObject.put(key.toString(), value.toString()); + } + vspObject.put("vspId", vspid); + vspObject.put("componentId", componentId); + vspObject.put("vendorName", amdocsLicenseMembers.getVendorLicenseName()); + vspObject.put("attContact", user.getUserId()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspid, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(vspid, user); + assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); + + Pair> pair = new Pair>(vspName, vspObject); + + return pair; + } + + public static void updateVspWithVfcArtifacts(String filepath, String vspId, String updatedSnmpPoll, String updatedSnmpTrap, String componentId, User user) throws Exception{ + RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); + ExtentTestActions.log(Status.INFO, "Deleting SNMP POLL"); + deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_POLL); + ExtentTestActions.log(Status.INFO, "Deleting SNMP TRAP"); + deleteSnmpArtifact(componentId, vspId, user, SnmpTypeEnum.SNMP_TRAP); + addVFCArtifacts(filepath, updatedSnmpPoll, updatedSnmpTrap, vspId, user, componentId); + prepareVspForUse(user, vspId); + } + + public static String updateVendorSoftwareProduct(String vspId, String HeatFileName, String filepath, User user) + throws Exception, Throwable { + String vspName = handleFilename(HeatFileName); + ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to update the vendor software product"); + + RestResponse checkout = checkoutVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checkout new VSP", 200, checkout.getErrorCode().intValue()); + + RestResponse uploadHeatPackage = uploadHeatPackage(filepath, HeatFileName, vspId, user); + assertEquals("did not succeed to upload HEAT package", 200, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = validateUpload(vspId, user); + assertEquals("did not succeed to validate upload process", 200, validateUpload.getErrorCode().intValue()); + + RestResponse checkin = checkinVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to checking VSP", 200, checkin.getErrorCode().intValue()); + + + RestResponse submit = submitVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to submit VSP", 200, submit.getErrorCode().intValue()); + + RestResponse createPackage = createPackageOfVendorSoftwareProduct(vspId, user); + assertEquals("did not succeed to update package of VSP ", 200, createPackage.getErrorCode().intValue()); + + ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in updating the vendor software product"); + + return vspName; + } + + public static String handleFilename(String heatFileName) { + final String namePrefix = "ciVFOnboarded-"; + final String nameSuffix = "-" + getShortUUID(); + + String subHeatFileName = heatFileName.substring(0, heatFileName.lastIndexOf(".")); + + if ((namePrefix + subHeatFileName + nameSuffix).length() >= 50) { + subHeatFileName = subHeatFileName.substring(0, 50 - namePrefix.length() - nameSuffix.length()); + } + + if (subHeatFileName.contains("(") || subHeatFileName.contains(")")) { + subHeatFileName = subHeatFileName.replace("(", "-"); + subHeatFileName = subHeatFileName.replace(")", "-"); + } + + String vnfName = namePrefix + subHeatFileName + nameSuffix; + return vnfName; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user, String vspComponentId) throws Exception{ + vspComponentId = (vspComponentId == null) ? getVSPComponentId(vspid, user) : vspComponentId; + if (vspComponentId != null){ + if (snmpPoll != null){ + ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP POLL with the file " + snmpPoll); + RestResponse uploadSnmpPollArtifact = uploadSnmpPollArtifact(filepath, snmpPoll, vspid, user, vspComponentId); + assertEquals("Did not succeed to add SNMP POLL", 200, uploadSnmpPollArtifact.getErrorCode().intValue()); + } + if (snmpTrap != null){ + ExtentTestActions.log(Status.INFO, "Adding VFC artifact of type SNMP TRAP with the file " + snmpTrap); + RestResponse uploadSnmpTrapArtifact = uploadSnmpTrapArtifact(filepath, snmpTrap, vspid, user, vspComponentId); + assertEquals("Did not succeed to add SNMP TRAP", 200, uploadSnmpTrapArtifact.getErrorCode().intValue()); + } + } + + return vspComponentId; + } + + public static String addVFCArtifacts(String filepath, String snmpPoll, String snmpTrap, String vspid, User user) throws Exception{ + return addVFCArtifacts(filepath, snmpPoll, snmpTrap, vspid, user, null); + } + + private static RestResponse uploadSnmpPollArtifact(String filepath, String zipArtifact, String vspid, User user, + String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { + Config config = Utils.getConfig(); + String snmpPollUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp/upload", + config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); + return uploadFile(filepath, zipArtifact, snmpPollUrl, user); + } + + private static RestResponse uploadSnmpTrapArtifact(String filepath, String zipArtifact, String vspid, User user, + String vspComponentId) throws FileNotFoundException, IOException, ClientProtocolException { + Config config = Utils.getConfig(); + String snmpTrapUrl = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/snmp-trap/upload", + config.getCatalogBeHost(),config.getCatalogBePort(), vspid, vspComponentId); + return uploadFile(filepath, zipArtifact, snmpTrapUrl, user); + } + + private static RestResponse deleteSnmpArtifact(String componentId, String vspId, User user, SnmpTypeEnum snmpType) throws Exception + { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components/%s/monitors/%s", + config.getCatalogBeHost(),config.getCatalogBePort(), vspId, componentId, snmpType.getValue()); + String userId = user.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendDelete(url, headersMap); + return response; + } + + + + private static String getVSPComponentId(String vspid, User user) throws Exception, JSONException { + RestResponse components = getVSPComponents(vspid, user); + String response = components.getResponse(); + Map responseMap = (Map) JSONValue.parse(response); + JSONArray results = (JSONArray)responseMap.get("results"); + for (Object res : results){ + Map compMap= (Map) JSONValue.parse(res.toString()); + String componentId = compMap.get("id").toString(); + return componentId; + } + return null; + } + + private static RestResponse getVSPComponents(String vspid, User user) throws Exception{ + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/components", config.getCatalogBeHost(),config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendGet(url, headersMap); + return response; + } + + public static AmdocsLicenseMembers createVendorLicense(User user) throws Exception { + + AmdocsLicenseMembers amdocsLicenseMembers; + ComponentBaseTest.getExtendTest().log(Status.INFO, "Starting to create the vendor license"); + String vendorLicenseName = "ciLicense" + getShortUUID(); + RestResponse vendorLicenseResponse = createVendorLicenseModels_1(vendorLicenseName, user); + assertEquals("did not succeed to create vendor license model", 200, vendorLicenseResponse.getErrorCode().intValue()); + String vendorId = ResponseParser.getValueFromJsonResponse(vendorLicenseResponse.getResponse(), "value"); + + RestResponse vendorKeyGroupsResponse = createVendorKeyGroups_2(vendorId, user); + assertEquals("did not succeed to create vendor key groups", 200, vendorKeyGroupsResponse.getErrorCode().intValue()); + String keyGroupId = ResponseParser.getValueFromJsonResponse(vendorKeyGroupsResponse.getResponse(), "value"); + + RestResponse vendorEntitlementPool = createVendorEntitlementPool_3(vendorId, user); + assertEquals("did not succeed to create vendor entitlement pool", 200, vendorEntitlementPool.getErrorCode().intValue()); + String entitlementPoolId = ResponseParser.getValueFromJsonResponse(vendorEntitlementPool.getResponse(), "value"); + + RestResponse vendorLicenseFeatureGroups = createVendorLicenseFeatureGroups_4(vendorId, keyGroupId, entitlementPoolId, user); + assertEquals("did not succeed to create vendor license feature groups", 200, vendorLicenseFeatureGroups.getErrorCode().intValue()); + String featureGroupId = ResponseParser.getValueFromJsonResponse(vendorLicenseFeatureGroups.getResponse(), "value"); + + RestResponse vendorLicenseAgreement = createVendorLicenseAgreement_5(vendorId, featureGroupId, user); + assertEquals("did not succeed to create vendor license agreement", 200, vendorLicenseAgreement.getErrorCode().intValue()); + String vendorLicenseAgreementId = ResponseParser.getValueFromJsonResponse(vendorLicenseAgreement.getResponse(), "value"); + + RestResponse checkinVendorLicense = checkinVendorLicense(vendorId, user); + assertEquals("did not succeed to checkin vendor license", 200, checkinVendorLicense.getErrorCode().intValue()); + + RestResponse submitVendorLicense = submitVendorLicense(vendorId, user); + assertEquals("did not succeed to submit vendor license", 200, submitVendorLicense.getErrorCode().intValue()); + + ComponentBaseTest.getExtendTest().log(Status.INFO, "Succeeded in creating the vendor license"); + + amdocsLicenseMembers = new AmdocsLicenseMembers(vendorId, vendorLicenseName, vendorLicenseAgreementId, featureGroupId); + + return amdocsLicenseMembers; + } + + private static String getShortUUID() { + return UUID.randomUUID().toString().split("-")[0]; + } + + private static RestResponse actionOnComponent(String vspid, String action, String onboardComponent, User user) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/" + onboardComponent + "/%s/versions/0.1/actions", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("action", action); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPut(url, jObject.toString(), headersMap); + return response; + } + + public static RestResponse checkinVendorLicense(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkin", "vendor-license-models", user); + } + + public static RestResponse submitVendorLicense(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Submit", "vendor-license-models", user); + } + + public static RestResponse createVendorLicenseModels_1(String name, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models", config.getCatalogBeHost(), + config.getCatalogBePort()); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("vendorName", name); + jObject.put("description", "new vendor license model"); + jObject.put("iconRef", "icon"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorLicenseAgreement_5(String vspid, String featureGroupId, User user) + throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-agreements", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject licenseTermpObject = new JSONObject(); + licenseTermpObject.put("choice", "Fixed_Term"); + licenseTermpObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "abc"); + jObjectBody.put("description", "new vendor license agreement"); + jObjectBody.put("requirementsAndConstrains", "abc"); + jObjectBody.put("licenseTerm", licenseTermpObject); + jObjectBody.put("addedFeatureGroupsIds", Arrays.asList(featureGroupId).toArray()); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorLicenseFeatureGroups_4(String vspid, String licenseKeyGroupId, + String entitlementPoolId, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/feature-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jObject = new JSONObject(); + jObject.put("name", "xyz"); + jObject.put("description", "new vendor license feature groups"); + jObject.put("partNumber", "123abc456"); + jObject.put("manufacturerReferenceNumber", "5"); + jObject.put("addedLicenseKeyGroupsIds", Arrays.asList(licenseKeyGroupId).toArray()); + jObject.put("addedEntitlementPoolsIds", Arrays.asList(entitlementPoolId).toArray()); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return response; + + } + + public static RestResponse createVendorEntitlementPool_3(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/entitlement-pools", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jEntitlementMetricObject = new JSONObject(); + jEntitlementMetricObject.put("choice", "CPU"); + jEntitlementMetricObject.put("other", ""); + + JSONObject jAggregationFunctionObject = new JSONObject(); + jAggregationFunctionObject.put("choice", "Peak"); + jAggregationFunctionObject.put("other", ""); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Availability_Zone").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jTimeObject = new JSONObject(); + jTimeObject.put("choice", "Hour"); + jTimeObject.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "def"+ getShortUUID()); + jObjectBody.put("description", "new vendor license entitlement pool"); + jObjectBody.put("thresholdValue", "23"); + jObjectBody.put("thresholdUnits", "Absolute"); + jObjectBody.put("entitlementMetric", jEntitlementMetricObject); + jObjectBody.put("increments", "abcd"); + jObjectBody.put("aggregationFunction", jAggregationFunctionObject); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("time", jTimeObject); + jObjectBody.put("manufacturerReferenceNumber", "123aaa"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static RestResponse createVendorKeyGroups_2(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-license-models/%s/versions/0.1/license-key-groups", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + String userId = user.getUserId(); + + JSONObject jOperationalScope = new JSONObject(); + jOperationalScope.put("choices", Arrays.asList("Tenant").toArray()); + jOperationalScope.put("other", ""); + + JSONObject jObjectBody = new JSONObject(); + jObjectBody.put("name", "keyGroup" + getShortUUID()); + jObjectBody.put("description", "new vendor license key group"); + jObjectBody.put("operationalScope", jOperationalScope); + jObjectBody.put("type", "Universal"); + + Map headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse response = http.httpSendPost(url, jObjectBody.toString(), headersMap); + return response; + } + + public static Pair> createNewVendorSoftwareProduct(String name, AmdocsLicenseMembers amdocsLicenseMembers, User user) throws Exception { + Map vspMetadta = new HashMap(); + + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products", + config.getCatalogBeHost(), config.getCatalogBePort()); + + String userId = user.getUserId(); + + JSONObject jlicensingDataObj = new JSONObject(); + jlicensingDataObj.put("licenseAgreement", amdocsLicenseMembers.getVendorLicenseAgreementId()); + jlicensingDataObj.put("featureGroups", Arrays.asList(amdocsLicenseMembers.getFeatureGroupId()).toArray()); + + JSONObject jlicensingVersionObj = new JSONObject(); + jlicensingVersionObj.put("id", "1.0"); + jlicensingVersionObj.put("label", "1.0"); + + JSONObject jObject = new JSONObject(); + jObject.put("name", name); + jObject.put("description", "new VSP description"); + jObject.put("category", "resourceNewCategory.generic"); + jObject.put("subCategory", "resourceNewCategory.generic.database"); + jObject.put("onboardingMethod", "HEAT"); + jObject.put("licensingVersion", jlicensingVersionObj); + jObject.put("vendorName", amdocsLicenseMembers.getVendorLicenseName()); + jObject.put("vendorId", amdocsLicenseMembers.getVendorId()); + jObject.put("icon", "icon"); + jObject.put("licensingData", jlicensingDataObj); + + vspMetadta.put("description", jObject.getString("description")); + vspMetadta.put("category", jObject.getString("category")); + vspMetadta.put("subCategory", jObject.getString("subCategory").split("\\.")[2]); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + RestResponse response = http.httpSendPost(url, jObject.toString(), headersMap); + return new Pair>(response, vspMetadta); + } + + public static RestResponse validateUpload(String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate/process", + config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + + String userId = user.getUserId(); + + Map headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + + String body =null; + + RestResponse response = http.httpSendPut(url, body, headersMap); + + return response; + } + + public static RestResponse uploadHeatPackage(String filepath, String filename, String vspid, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format("http://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/0.1/orchestration-template-candidate", config.getCatalogBeHost(), config.getCatalogBePort(), vspid); + return uploadFile(filepath, filename, url, user); + } + + private static RestResponse uploadFile(String filepath, String filename, String url, User user) + throws FileNotFoundException, IOException, ClientProtocolException { + CloseableHttpResponse response = null; + + MultipartEntityBuilder mpBuilder = MultipartEntityBuilder.create(); + mpBuilder.addPart("upload", new FileBody(getTestZipFile(filepath, filename))); + + Map headersMap = prepareHeadersMap(user.getUserId()); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "multipart/form-data"); + + CloseableHttpClient client = HttpClients.createDefault(); + try { + HttpPost httpPost = new HttpPost(url); + RestResponse restResponse = new RestResponse(); + + Iterator iterator = headersMap.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + String value = headersMap.get(key); + httpPost.addHeader(key, value); + } + httpPost.setEntity(mpBuilder.build()); + response = client.execute(httpPost); + HttpEntity entity = response.getEntity(); + String responseBody = null; + if (entity != null) { + InputStream instream = entity.getContent(); + StringWriter writer = new StringWriter(); + IOUtils.copy(instream, writer); + responseBody = writer.toString(); + try { + + } finally { + instream.close(); + } + } + + restResponse.setErrorCode(response.getStatusLine().getStatusCode()); + restResponse.setResponse(responseBody); + + return restResponse; + + } finally { + closeResponse(response); + closeHttpClient(client); + + } + } + + private static void closeResponse(CloseableHttpResponse response) { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static void closeHttpClient(CloseableHttpClient client) { + try { + if (client != null) { + client.close(); + } + } catch (IOException e) { + System.out.println(String.format("failed to close client or response: %s", e.getMessage())); + } + } + + private static File getTestZipFile(String filepath, String filename) throws IOException { + Config config = Utils.getConfig(); + String sourceDir = config.getImportResourceTestsConfigDir(); + java.nio.file.Path filePath = FileSystems.getDefault().getPath(filepath + File.separator + filename); + return filePath.toFile(); + } + + public static RestResponse checkinVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkin", "vendor-software-products", user); + } + + private static RestResponse checkoutVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Checkout", "vendor-software-products", user); + } + + public static RestResponse submitVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Submit", "vendor-software-products", user); + } + + public static RestResponse createPackageOfVendorSoftwareProduct(String vspid, User user) throws Exception { + return actionOnComponent(vspid, "Create_Package", "vendor-software-products", user); + } + + protected static Map prepareHeadersMap(String userId) { + Map headersMap = new HashMap(); + headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), "application/json"); + headersMap.put(HttpHeaderEnum.USER_ID.getValue(), userId); + return headersMap; + } + + +// private static void importUpdateVSP(Pair> vsp, boolean isUpdate) throws Exception{ +// String vspName = vsp.left; +// Map vspMetadata = vsp.right; +// boolean vspFound = HomePage.searchForVSP(vspName); +// +// if (vspFound){ +// +// List elemenetsFromTable = HomePage.getElemenetsFromTable(); +//// WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), 30); +//// WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elemenetsFromTable.get(1))); +//// findElement.click(); +// elemenetsFromTable.get(1).click(); +// GeneralUIUtils.waitForLoader(); +// +// if (isUpdate){ +// GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); +// +// } +// else{ +// GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); +// } +// +// String lifeCycleState = ResourceGeneralPage.getLifeCycleState(); +// boolean needCheckout = lifeCycleState.equals(LifeCycleStateEnum.CHECKIN.getValue()) || lifeCycleState.equals(LifeCycleStateEnum.CERTIFIED.getValue()); +// if (needCheckout) +// { +// try { +// ResourceGeneralPage.clickCheckoutButton(); +// Assert.assertTrue(ResourceGeneralPage.getLifeCycleState().equals(LifeCycleStateEnum.CHECKOUT.getValue()), "Did not succeed to checkout"); +// +// } catch (Exception e) { +// ExtentTestActions.log(Status.ERROR, "Did not succeed to checkout"); +// e.printStackTrace(); +// } +// GeneralUIUtils.waitForLoader(); +// } +// +// //Metadata verification +// VfVerificator.verifyOnboardedVnfMetadata(vspName, vspMetadata); +// +// ExtentTestActions.log(Status.INFO, "Clicking create/update VNF"); +// String duration = GeneralUIUtils.getActionDuration(() -> waitUntilVnfCreated()); +// ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration); +// } +// else{ +// Assert.fail("Did not find VSP named " + vspName); +// } +// } + +// private static void waitUntilVnfCreated() { +// GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); +// GeneralUIUtils.waitForLoader(60*10); +// GeneralUIUtils.waitForAngular(); +// GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); +// } +// +// public static void updateVSP(Pair> vsp) throws Exception{ +// ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.left); +// importUpdateVSP(vsp, true); +// } +// +// public static void importVSP(Pair> vsp) throws Exception{ +// ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.left); +// importUpdateVSP(vsp, false); +// } +// +// public static void updateVnfAndValidate(String filepath, Pair> vsp, String updatedVnfFile, User user) throws Exception, Throwable { +// ExtentTestActions.log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile)); +// System.out.println(String.format("Going to update the VNF with %s......", updatedVnfFile)); +// +// Map vspMap = vsp.right; +// String vspId = vspMap.get("vspId"); +// +// updateVendorSoftwareProduct(vspId, updatedVnfFile, filepath, user); +// HomePage.showVspRepository(); +// updateVSP(vsp); +// ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); +// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, updatedVnfFile); +// } +// +// public static Pair> onboardAndValidate(String filepath, String vnfFile, User user) throws Exception { +// ExtentTestActions.log(Status.INFO, String.format("Going to onboard the VNF %s", vnfFile)); +// System.out.println(String.format("Going to onboard the VNF %s", vnfFile)); +// +// AmdocsLicenseMembers amdocsLicenseMembers = createVendorLicense(user); +// Pair> createVendorSoftwareProduct = createVendorSoftwareProduct(vnfFile, filepath, user, amdocsLicenseMembers); +// String vspName = createVendorSoftwareProduct.left; +// +// DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.right.get("vspId")); +// File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); +// +// ExtentTestActions.log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); +// HomePage.showVspRepository(); +// ExtentTestActions.log(Status.INFO,String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf(".")))); +// importVSP(createVendorSoftwareProduct); +// +// ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); +// +// // Verify deployment artifacts +// Map combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); +// +// LinkedList deploymentArtifacts = ((LinkedList) combinedMap.get("Deployment")); +// ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts); +// +// List heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")). +// map(e -> e.getFileName()). +// collect(Collectors.toList()); +// +// validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR); +// +// DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); +// return createVendorSoftwareProduct; +// } +// +// public static void validateDeploymentArtifactsVersion(LinkedList deploymentArtifacts, +// List heatEnvFilesFromCSAR) { +// String artifactVersion; +// String artifactName; +// +// for(HeatMetaFirstLevelDefinition deploymentArtifact: deploymentArtifacts) { +// artifactVersion = "1"; +// +// if(deploymentArtifact.getType().equals("HEAT_ENV")) { +// continue; +// } else if(deploymentArtifact.getFileName().contains(".")) { +// artifactName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")); +// } else { +// artifactName = deploymentArtifact.getFileName().trim(); +// } +// +// if (heatEnvFilesFromCSAR.contains(artifactName + ".env")){ +// artifactVersion = "2"; +// } +// ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType()); +// } +// } + + + /** + * @return + * The method returns VNF names list from Files directory under sdc-vnfs repository + */ + public static List getVnfNamesFileList() { + String filepath = FileHandling.getVnfRepositoryPath(); + List fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath); + fileNamesFromFolder.removeAll(exludeVnfList); + return fileNamesFromFolder; + } + + /** + * @return + * The method returns VNF names list from Files directory under sdc-vnfs repository excluding zip files that known as failed in tosca parser + */ + public static List getVnfNamesFileListExcludeToscaParserFailure() { + List fileNamesFromFolder = getVnfNamesFileList(); + fileNamesFromFolder.removeAll(exludeVnfListForToscaParser); + return fileNamesFromFolder; + } + +} + + \ No newline at end of file diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java new file mode 100644 index 0000000000..71038920ae --- /dev/null +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/general/SnmpTypeEnum.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.ci.tests.utils.general; + +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.simple.JSONArray; +import org.json.simple.JSONValue; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.ci.tests.config.Config; +import org.openecomp.sdc.ci.tests.datatypes.AmdocsLicenseMembers; + +import org.openecomp.sdc.ci.tests.datatypes.HeatMetaFirstLevelDefinition; + +import org.openecomp.sdc.ci.tests.datatypes.http.HttpHeaderEnum; +import org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest; +import org.openecomp.sdc.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.ci.tests.execute.devCI.ArtifactFromCsar; + + +import org.openecomp.sdc.ci.tests.utils.Utils; +import org.openecomp.sdc.ci.tests.utils.rest.ResponseParser; + +import org.testng.Assert; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; + +enum SnmpTypeEnum{ + SNMP_POLL ("snmp"), + SNMP_TRAP ("snmp-trap"); + + private String value; + + public String getValue() { + return value; + } + + private SnmpTypeEnum(String value) { + this.value = value; +} + +} + diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java index e08ef6523f..ec8fd4089a 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtils.java @@ -78,7 +78,7 @@ public class ResourceRestUtils extends BaseRestUtils { Gson gson = new Gson(); String userBodyJson = gson.toJson(resourceDetails); - String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson); headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); HttpRequest http = new HttpRequest(); // System.out.println(url); @@ -490,7 +490,7 @@ public class ResourceRestUtils extends BaseRestUtils { Gson gson = new Gson(); String userBodyJson = gson.toJson(resourceDetails); - String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson); headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); HttpRequest http = new HttpRequest(); RestResponse updateResourceResponse = http.httpSendPut(url, userBodyJson, headersMap); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java index 10f573cf0e..19d7d728fe 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/ci/tests/utils/rest/ResourceRestUtilsExternalAPI.java @@ -48,7 +48,7 @@ public class ResourceRestUtilsExternalAPI extends BaseRestUtils { Gson gson = new Gson(); String userBodyJson = gson.toJson(resourceDetails); - String calculateMD5 = GeneralUtility.calculateMD5ByString(userBodyJson); + String calculateMD5 = GeneralUtility.calculateMD5Base64EncodedByString(userBodyJson); headersMap.put(HttpHeaderEnum.Content_MD5.getValue(), calculateMD5); headersMap.put(HttpHeaderEnum.AUTHORIZATION.getValue(), authorizationHeader); headersMap.put(HttpHeaderEnum.X_ECOMP_INSTANCE_ID.getValue(), "ci"); diff --git a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java index 61b7ea18d2..9ba6953bb3 100644 --- a/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java +++ b/test-apis-ci/src/main/java/org/openecomp/sdc/externalApis/CRUDExternalAPI.java @@ -3377,7 +3377,7 @@ public class CRUDExternalAPI extends ComponentBaseTest { httppost.addHeader(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); httppost.addHeader(HttpHeaderEnum.USER_ID.getValue(), sdncUserDetails.getUserId()); if (addMd5Header) { - httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5ByString(jsonBody)); + httppost.addHeader(HttpHeaderEnum.Content_MD5.getValue(), GeneralUtility.calculateMD5Base64EncodedByString(jsonBody)); } StringEntity input = new StringEntity(jsonBody); input.setContentType("application/json"); -- cgit 1.2.3-korg