diff options
author | JulienBe <julien.bertozzi@intl.att.com> | 2020-08-25 22:20:30 +0200 |
---|---|---|
committer | Christophe Closset <christophe.closset@intl.att.com> | 2020-09-02 06:55:42 +0000 |
commit | 930ed2515529bd7ff054b083816587b6d46f56b5 (patch) | |
tree | f6609e186e4c15c6149ebc1196c89fa1175c978d /integration-tests/src/test/java | |
parent | 6912567fc8eb045cc10868a01fb62dfbb2cd9937 (diff) |
Add sdc startup in IT
Add the UI part with the latest selenium and firefox driver in headless
Issue-ID: SDC-3232
Signed-off-by: sebdet <sebastien.determe@intl.att.com>
Change-Id: I5c5da5a26eda3042d94995f67937c105edef74c0
Signed-off-by: JulienBe <julien.bertozzi@intl.att.com>
Diffstat (limited to 'integration-tests/src/test/java')
175 files changed, 34421 insertions, 1018 deletions
diff --git a/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/config/Config.java b/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/config/Config.java index f8368bd682..fcf79e529f 100644 --- a/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/config/Config.java +++ b/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/config/Config.java @@ -7,9 +7,9 @@ * 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. @@ -31,706 +31,651 @@ import java.util.List; public class Config { - private static String WINDOWS_CONFIG_FILE = "src/test/resources/ci/conf/attsdc.yaml"; - private boolean systemUnderDebug; - private boolean rerun; - private String reportDBhost; - private int reportDBport; - - private String browser; - private String catalogBeHost; - private String esHost; - private String esPort; - private String neoHost; - private String neoPort; - private String disributionClientHost; - private String disributionClientPort; - private boolean isDistributionClientRunning; - - - private String errorConfigurationFile; - private String resourceConfigDir; - private String componentsConfigDir; - private String importResourceConfigDir; - private String importResourceTestsConfigDir; - private String importTypesConfigDir; - - private String testSuites; - - private String catalogFeHost; - private String catalogFePort; - private String catalogBePort; - private String catalogBeTlsPort; - - private String onboardingBeHost; - private String onboardingBePort; - - private String neoDBusername; - private String neoDBpassword; - - private String janusGraphPropertiesFile; - private List<String> packages; - private List<String> bugs; - private List<String> resourcesNotToDelete; - private List<String> resourceCategoriesNotToDelete; - private List<String> serviceCategoriesNotToDelete; - private boolean stopOnClassFailure = false; - - private String outputFolder; - private String reportName; - private String url; - private String remoteTestingMachineIP; - private String remoteTestingMachinePort; - private boolean remoteTesting; - - private String cassandraHost; - private String cassandraAuditKeySpace; - private String cassandraArtifactKeySpace; - private boolean cassandraAuthenticate; - private String cassandraUsername; - private String cassandraPassword; - private boolean cassandraSsl; - private String cassandraTruststorePath; - private String cassandraTruststorePassword; - private String windowsDownloadDirectory; - private boolean captureTraffic; - private boolean useBrowserMobProxy; - private String sdcHttpMethod; - private String localDataCenter; - private boolean uiSimulator; - - public String getLocalDataCenter() { - return localDataCenter; - } - - public void setLocalDataCenter(String localDataCenter) { - this.localDataCenter = localDataCenter; - } - - private static Config configIt = null; - - private static Yaml yaml = new Yaml(); - - - private Config() { - super(); - } - - public String getOnboardingBePort() { - return onboardingBePort; - } - - public void setOnboardingBePort(String onboardingBePort) { - this.onboardingBePort = onboardingBePort; - } - - public String getOnboardingBeHost() { - return onboardingBeHost; - } - - public void setOnboardingBeHost(String onboardingBeHost) { - this.onboardingBeHost = onboardingBeHost; - } - - public static class TestPackages { - - List<String> packages; - List<String> bugs; - - public List<String> getPackages() { - return packages; - } - - public void setPackages(List<String> packages) { - this.packages = packages; - } - - public List<String> getBugs() { - return bugs; - } - - public void setBugs(List<String> bugs) { - this.bugs = bugs; - } - - @Override - public String toString() { - return "TestPackages [packages=" + packages + ", bugs=" + bugs + "]"; - } - - } - - public synchronized static Config instance() { - if (configIt == null) { - try { - configIt = init(); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - } - return configIt; - } - - private static Config init() throws IOException { - - Config config = null; - - String configFile = System.getProperty("config.resource"); - if (configFile == null) { - configFile = WINDOWS_CONFIG_FILE; - } - - File file = new File(configFile); - if (false == file.exists()) { - throw new RuntimeException("The config file " + configFile + " cannot be found."); - } - - InputStream in = null; - try { - - in = Files.newInputStream(Paths.get(configFile)); - - config = yaml.loadAs(in, Config.class); - - setPackagesAndBugs(configFile, config); - - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - // JsonReader jsonReader = new JsonReader(new FileReader(configFile)); - // Config configAttOdlIt = new Gson().fromJson(jsonReader, - // Config.class); - - return config; - } - - public boolean isUiSimulator() { - return uiSimulator; - } - - public void setUiSimulator(boolean uiSimulator) { - this.uiSimulator = uiSimulator; - } - - private static void setPackagesAndBugs(String path, Config config) throws IOException { - - int separator = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/")); - String dirPath = path.substring(0, separator + 1); - String packagesFile = dirPath + File.separator + "attsdc-packages.yaml"; - File file = new File(packagesFile); - if (false == file.exists()) { - throw new RuntimeException("The config file " + packagesFile + " cannot be found."); - } - - TestPackages testPackages = null; - InputStream in = null; - try { - - in = Files.newInputStream(Paths.get(packagesFile)); - - testPackages = yaml.loadAs(in, TestPackages.class); - - List<String> bugs = testPackages.getBugs(); - List<String> packages = testPackages.getPackages(); - - config.setBugs(bugs); - config.setPackages(packages); - - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - } - - // public Config(String catalogBeHost, String esHost, String esPort, String - // resourceConfigDir, String componentsConfigDir, String catalogFeHost, - // String catalogFePort, String catalogBePort) { - // super(); - // this.catalogBeHost = catalogBeHost; - // this.esHost = esHost; - // this.esPort = esPort; - // this.resourceConfigDir = resourceConfigDir; - // this.componentsConfigDir = componentsConfigDir; - // this.catalogFeHost = catalogFeHost; - // this.catalogFePort = catalogFePort; - // this.catalogBePort = catalogBePort; - // } - - String configurationFile; - - public boolean getSystemUnderDebug() { - return systemUnderDebug; - } - - public void setSystemUnderDebug(boolean systemUnderDebug) { - this.systemUnderDebug = systemUnderDebug; - } - - public String getSdcHttpMethod() { - return sdcHttpMethod; - } - - public void setSdcHttpMethod(String sdcHttpMethod) { - this.sdcHttpMethod = sdcHttpMethod; - } - - public boolean getRerun() { - return rerun; - } - - public void setRerun(boolean rerun) { - this.rerun = rerun; - } - - public String getReportDBhost() { - return reportDBhost; - } - - public void setReportDBhost(String reportDBhost) { - this.reportDBhost = reportDBhost; - } - - public int getReportDBport() { - return reportDBport; - } - - public void setReportDBport(int reportDBport) { - this.reportDBport = reportDBport; - } -// public boolean isUsingBrowserMobProxy() { -// return useBrowserMobProxy; -// } -// -// public void setUsingBrowserMobProxy(boolean usingBrowserMobProxy) { -// this.useBrowserMobProxy = usingBrowserMobProxy; -// } - - - - - public String getBrowser() { - return browser; - } - - public boolean getUseBrowserMobProxy() { - return useBrowserMobProxy; - } - - public void setUseBrowserMobProxy(boolean useBrowserMobProxy) { - this.useBrowserMobProxy = useBrowserMobProxy; - } - - - - public boolean getCaptureTraffic() { - return captureTraffic; - } - - public void setCaptureTraffic(boolean captureTraffic) { - this.captureTraffic = captureTraffic; - } - - public void setBrowser(String browser) { - this.browser = browser; - } - - public String getConfigurationFile() { - return configurationFile; - } - - public void setConfigurationFile(String configurationFile) { - this.configurationFile = configurationFile; - } - - public boolean getIsDistributionClientRunning() { - return isDistributionClientRunning; - } - - public void setIsDistributionClientRunning(boolean isDistributionClientRunning) { - this.isDistributionClientRunning = isDistributionClientRunning; - } - - public String getCatalogBePort() { - return catalogBePort; - } - - public String getDisributionClientHost() { - return disributionClientHost; - } - - public void setDisributionClientHost(String disributionClientHost) { - this.disributionClientHost = disributionClientHost; - } - - public String getDisributionClientPort() { - return disributionClientPort; - } - - public void setDisributionClientPort(String disributionClientPort) { - this.disributionClientPort = disributionClientPort; - } - - public void setCatalogBePort(String catalogBePort) { - this.catalogBePort = catalogBePort; - } - - public String getCatalogFeHost() { - return catalogFeHost; - } - - public void setCatalogFeHost(String catalogFeHost) { - this.catalogFeHost = catalogFeHost; - } - - public String getCatalogFePort() { - return catalogFePort; - } - - public void setCatalogFePort(String catalogFePort) { - this.catalogFePort = catalogFePort; - } - - public String getCatalogBeHost() { - return catalogBeHost; - } - - public void setCatalogBeHost(String catalogBeHost) { - this.catalogBeHost = catalogBeHost; - } - - public String getEsHost() { - return esHost; - } - - public void setEsHost(String esHost) { - this.esHost = esHost; - } - - public String getEsPort() { - return esPort; - } + private static String SDC_DEFAULT_CONFIG_FILE = "src/test/resources/ci/conf/sdc-conf.yaml"; + private String downloadAutomationFolder; + private boolean systemUnderDebug; + private boolean rerun; + private String reportDBhost; + private int reportDBport; + + private String browser; + private String catalogBeHost; + private String esHost; + private String esPort; + private String neoHost; + private String neoPort; + private String disributionClientHost; + private String disributionClientPort; + private boolean isDistributionClientRunning; + + + private String errorConfigurationFile; + private String resourceConfigDir; + private String importResourceConfigDir; + private String importResourceTestsConfigDir; + + private String catalogFeHost; + private String catalogFePort; + private String catalogBePort; + private String catalogBeTlsPort; + + private String onboardingBeHost; + private String onboardingBePort; + + private String neoDBusername; + private String neoDBpassword; + + private List<String> packages; + private List<String> bugs; + private List<String> resourcesNotToDelete; + private List<String> resourceCategoriesNotToDelete; + private List<String> serviceCategoriesNotToDelete; + private boolean stopOnClassFailure = false; + + private String outputFolder; + private String reportName; + private String url; + private String remoteTestingMachineIP; + private String remoteTestingMachinePort; + private boolean remoteTesting; + + private String cassandraHost; + private String cassandraAuditKeySpace; + private String cassandraArtifactKeySpace; + private boolean cassandraAuthenticate; + private String cassandraUsername; + private String cassandraPassword; + private boolean cassandraSsl; + private String cassandraTruststorePath; + private String cassandraTruststorePassword; + private boolean captureTraffic; + private boolean useBrowserMobProxy; + private String sdcHttpMethod; + private String localDataCenter; + private boolean uiSimulator; + + public String getLocalDataCenter() { + return localDataCenter; + } + + public void setLocalDataCenter(String localDataCenter) { + this.localDataCenter = localDataCenter; + } + + private static Config configIt = null; + + private static Yaml yaml = new Yaml(); + + + private Config() { + super(); + } + + public String getOnboardingBePort() { + return onboardingBePort; + } + + public void setOnboardingBePort(String onboardingBePort) { + this.onboardingBePort = onboardingBePort; + } + + public String getOnboardingBeHost() { + return onboardingBeHost; + } + + public void setOnboardingBeHost(String onboardingBeHost) { + this.onboardingBeHost = onboardingBeHost; + } + + public static class TestPackages { + + List<String> packages; + List<String> bugs; + + public List<String> getPackages() { + return packages; + } + + public void setPackages(List<String> packages) { + this.packages = packages; + } + + public List<String> getBugs() { + return bugs; + } + + public void setBugs(List<String> bugs) { + this.bugs = bugs; + } + + @Override + public String toString() { + return "TestPackages [packages=" + packages + ", bugs=" + bugs + "]"; + } + + } + + public synchronized static Config instance() { + if (configIt == null) { + try { + configIt = init(); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } + return configIt; + } + + private static Config init() throws IOException { + + Config config = null; + + String configFile = System.getProperty("config.resource"); + if (configFile == null) { + configFile = SDC_DEFAULT_CONFIG_FILE; + } + + File file = new File(configFile); + if (false == file.exists()) { + throw new RuntimeException("The config file " + configFile + " cannot be found."); + } - public void setEsPort(String esPort) { - this.esPort = esPort; - } + InputStream in = null; + try { - public String getResourceConfigDir() { - return resourceConfigDir; - } + in = Files.newInputStream(Paths.get(configFile)); - public void setResourceConfigDir(String resourceConfigDir) { - this.resourceConfigDir = resourceConfigDir; - } + config = yaml.loadAs(in, Config.class); - public String getComponentsConfigDir() { - return componentsConfigDir; - } + setPackagesAndBugs(configFile, config); - public void setComponentsConfigDir(String componentsConfigDir) { - this.componentsConfigDir = componentsConfigDir; - } + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } - public String getOutputFolder() { - return outputFolder; - } + // JsonReader jsonReader = new JsonReader(new FileReader(configFile)); + // Config configAttOdlIt = new Gson().fromJson(jsonReader, + // Config.class); - public void setOutputFolder(String outputFolder) { - this.outputFolder = outputFolder; - } + return config; + } - public String getReportName() { - return reportName; - } + public boolean isUiSimulator() { + return uiSimulator; + } - public void setReportName(String reportName) { - this.reportName = reportName; - } + public void setUiSimulator(boolean uiSimulator) { + this.uiSimulator = uiSimulator; + } - public String getNeoPort() { - return neoPort; - } + private static void setPackagesAndBugs(String path, Config config) throws IOException { - public void setNeoPort(String neoPort) { - this.neoPort = neoPort; - } + int separator = Math.max(path.lastIndexOf("\\"), path.lastIndexOf("/")); + String dirPath = path.substring(0, separator + 1); + String packagesFile = dirPath + File.separator + "sdc-packages.yaml"; + File file = new File(packagesFile); + if (false == file.exists()) { + throw new RuntimeException("The config file " + packagesFile + " cannot be found."); + } - public String getNeoHost() { - return neoHost; - } + TestPackages testPackages = null; + InputStream in = null; + try { - public void setNeoHost(String neoHost) { - this.neoHost = neoHost; - } + in = Files.newInputStream(Paths.get(packagesFile)); - public String getNeoDBpassword() { - return neoDBpassword; - } + testPackages = yaml.loadAs(in, TestPackages.class); - public String getNeoDBusername() { - return neoDBusername; - } + List<String> bugs = testPackages.getBugs(); + List<String> packages = testPackages.getPackages(); - public void setNeoDBusername(String neoDBusername) { - this.neoDBusername = neoDBusername; - } + config.setBugs(bugs); + config.setPackages(packages); - public void setNeoDBpassword(String neoDBpassword) { - this.neoDBpassword = neoDBpassword; - } + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } - public String getjanusGraphPropertiesFile() { - return janusGraphPropertiesFile; - } + } - public void setjanusGraphPropertiesFile(String janusGraphPropertiesFile) { - this.janusGraphPropertiesFile = janusGraphPropertiesFile; - } + String configurationFile; - public List<String> getPackages() { - return packages; - } + public boolean getSystemUnderDebug() { + return systemUnderDebug; + } - public void setPackages(List<String> packages) { - this.packages = packages; - } + public void setSystemUnderDebug(boolean systemUnderDebug) { + this.systemUnderDebug = systemUnderDebug; + } - public List<String> getBugs() { - return bugs; - } + public String getSdcHttpMethod() { + return sdcHttpMethod; + } - public void setBugs(List<String> bugs) { - this.bugs = bugs; - } + public void setSdcHttpMethod(String sdcHttpMethod) { + this.sdcHttpMethod = sdcHttpMethod; + } - public boolean isStopOnClassFailure() { - return stopOnClassFailure; - } - - public void setStopOnClassFailure(boolean stopOnClassFailure) { - this.stopOnClassFailure = stopOnClassFailure; - } - - public String getImportResourceConfigDir() { - return importResourceConfigDir; - } - - public void setImportResourceConfigDir(String importResourceConfigDir) { - this.importResourceConfigDir = importResourceConfigDir; - } - - public String getImportResourceTestsConfigDir() { - return importResourceTestsConfigDir; - } - - public void setImportResourceTestsConfigDir(String importResourceTestsConfigDir) { - this.importResourceTestsConfigDir = importResourceTestsConfigDir; - } - - public String getErrorConfigurationFile() { - return errorConfigurationFile; - } - - public void setErrorConfigurationFile(String errorConfigurationFile) { - this.errorConfigurationFile = errorConfigurationFile; - } - - public String getCatalogBeTlsPort() { - return catalogBeTlsPort; - } - - public void setCatalogBeTlsPort(String catalogBeTlsPort) { - this.catalogBeTlsPort = catalogBeTlsPort; - } - - public List<String> getResourcesNotToDelete() { - return resourcesNotToDelete; - } - - public void setResourcesNotToDelete(List<String> resourcesNotToDelete) { - this.resourcesNotToDelete = resourcesNotToDelete; - } - - public List<String> getResourceCategoriesNotToDelete() { - return resourceCategoriesNotToDelete; - } - - public void setResourceCategoriesNotToDelete(List<String> resourceCategoriesNotToDelete) { - this.resourceCategoriesNotToDelete = resourceCategoriesNotToDelete; - } - - public List<String> getServiceCategoriesNotToDelete() { - return serviceCategoriesNotToDelete; - } - - public void setServiceCategoriesNotToDelete(List<String> serviceCategoriesNotToDelete) { - this.serviceCategoriesNotToDelete = serviceCategoriesNotToDelete; - } - - public String getImportTypesConfigDir() { - return importTypesConfigDir; - } - - public void setImportTypesConfigDir(String importTypesConfigDir) { - this.importTypesConfigDir = importTypesConfigDir; - } - - public String getCassandraHost() { - return cassandraHost; - } - - public void setCassandraHost(String cassandraHost) { - this.cassandraHost = cassandraHost; - } - - public String getCassandraAuditKeySpace() { - return cassandraAuditKeySpace; - } - - public void setCassandraAuditKeySpace(String cassandraAuditKeySpace) { - this.cassandraAuditKeySpace = cassandraAuditKeySpace; - } - - public String getCassandraArtifactKeySpace() { - return cassandraArtifactKeySpace; - } - - public void setCassandraArtifactKeySpace(String cassandraArtifactKeySpace) { - this.cassandraArtifactKeySpace = cassandraArtifactKeySpace; - } - - - public String getWindowsDownloadDirectory() { - return windowsDownloadDirectory; - } - - public void setWindowsDownloadDirectory(String windowsDownloadDirectory) { - this.windowsDownloadDirectory = windowsDownloadDirectory; - } - - @Override - public String toString() { - return "Config [systemUnderDebug=" + systemUnderDebug + ", rerun=" + rerun + ", reportDBhost=" + reportDBhost - + ", reportDBport=" + reportDBport + ", browser=" + browser + ", catalogBeHost=" + catalogBeHost - + ", esHost=" + esHost + ", esPort=" + esPort + ", neoHost=" + neoHost + ", neoPort=" + neoPort - + ", disributionClientHost=" + disributionClientHost + ", disributionClientPort=" - + disributionClientPort + ", isDistributionClientRunning=" + isDistributionClientRunning - + ", errorConfigurationFile=" + errorConfigurationFile + ", resourceConfigDir=" + resourceConfigDir - + ", componentsConfigDir=" + componentsConfigDir + ", importResourceConfigDir=" - + importResourceConfigDir + ", importResourceTestsConfigDir=" + importResourceTestsConfigDir - + ", importTypesConfigDir=" + importTypesConfigDir + ", testSuites=" + testSuites + ", catalogFeHost=" - + catalogFeHost + ", catalogFePort=" + catalogFePort + ", catalogBePort=" + catalogBePort - + ", catalogBeTlsPort=" + catalogBeTlsPort + ", neoDBusername=" + neoDBusername + ", neoDBpassword=" - + neoDBpassword + ", janusGraphPropertiesFile=" + janusGraphPropertiesFile + ", packages=" + packages + ", bugs=" - + bugs + ", resourcesNotToDelete=" + resourcesNotToDelete + ", resourceCategoriesNotToDelete=" - + resourceCategoriesNotToDelete + ", serviceCategoriesNotToDelete=" + serviceCategoriesNotToDelete - + ", stopOnClassFailure=" + stopOnClassFailure + ", outputFolder=" + outputFolder + ", reportName=" - + reportName + ", url=" + url + ", remoteTestingMachineIP=" + remoteTestingMachineIP - + ", remoteTestingMachinePort=" + remoteTestingMachinePort + ", remoteTesting=" + remoteTesting - + ", cassandraHost=" + cassandraHost + ", cassandraAuditKeySpace=" + cassandraAuditKeySpace - + ", cassandraArtifactKeySpace=" + cassandraArtifactKeySpace + ", cassandraAuthenticate=" - + cassandraAuthenticate + ", cassandraUsername=" + cassandraUsername + ", cassandraPassword=" - + cassandraPassword + ", cassandraSsl=" + cassandraSsl + ", cassandraTruststorePath=" - + cassandraTruststorePath + ", cassandraTruststorePassword=" + cassandraTruststorePassword - + ", windowsDownloadDirectory=" + windowsDownloadDirectory + ", captureTraffic=" + captureTraffic - + ", useBrowserMobProxy=" + useBrowserMobProxy + ", configurationFile=" + configurationFile + "]"; - } - - public boolean isRemoteTesting() { - return remoteTesting; - } - - public void setRemoteTesting(boolean remoteTesting) { - this.remoteTesting = remoteTesting; - } - - public String getUrl() { - try { - return url; - } catch (Exception e) { - return null; - } - } - - public void setUrl(String url) { - this.url = url; - } - - public String getRemoteTestingMachineIP() { - return remoteTestingMachineIP; - } - - public void setRemoteTestingMachineIP(String remoteTestingMachineIP) { - this.remoteTestingMachineIP = remoteTestingMachineIP; - } - - public String getRemoteTestingMachinePort() { - return remoteTestingMachinePort; - } - - public void setRemoteTestingMachinePort(String remoteTestingMachinePort) { - this.remoteTestingMachinePort = remoteTestingMachinePort; - } - - public boolean getCassandraAuthenticate() { - return cassandraAuthenticate; - } - - public void setCassandraAuthenticate(boolean cassandraAuthenticate) { - this.cassandraAuthenticate = cassandraAuthenticate; - } - - public String getCassandraUsername() { - return cassandraUsername; - } - - public void setCassandraUsername(String cassandraUsername) { - this.cassandraUsername = cassandraUsername; - } - - public String getCassandraPassword() { - return cassandraPassword; - } - - public void setCassandraPassword(String cassandraPassword) { - this.cassandraPassword = cassandraPassword; - } - - public boolean getCassandraSsl() { - return cassandraSsl; - } - - public void setCassandraSsl(boolean cassandraSsl) { - this.cassandraSsl = cassandraSsl; - } - - public String getCassandraTruststorePath() { - return cassandraTruststorePath; - } - - public void setCassandraTruststorePath(String cassandraTruststorePath) { - this.cassandraTruststorePath = cassandraTruststorePath; - } - - public String getCassandraTruststorePassword() { - return cassandraTruststorePassword; - } - - public void setCassandraTruststorePassword(String cassandraTruststorePassword) { - this.cassandraTruststorePassword = cassandraTruststorePassword; - } + public boolean getRerun() { + return rerun; + } + + public void setRerun(boolean rerun) { + this.rerun = rerun; + } + + public String getReportDBhost() { + return reportDBhost; + } + + public void setReportDBhost(String reportDBhost) { + this.reportDBhost = reportDBhost; + } + + public int getReportDBport() { + return reportDBport; + } + + public void setReportDBport(int reportDBport) { + this.reportDBport = reportDBport; + } + + public String getBrowser() { + return browser; + } + + public boolean getUseBrowserMobProxy() { + return useBrowserMobProxy; + } + + public void setUseBrowserMobProxy(boolean useBrowserMobProxy) { + this.useBrowserMobProxy = useBrowserMobProxy; + } + + + public boolean getCaptureTraffic() { + return captureTraffic; + } + + public void setCaptureTraffic(boolean captureTraffic) { + this.captureTraffic = captureTraffic; + } + + public void setBrowser(String browser) { + this.browser = browser; + } + + public String getConfigurationFile() { + return configurationFile; + } + + public void setConfigurationFile(String configurationFile) { + this.configurationFile = configurationFile; + } + + public boolean getIsDistributionClientRunning() { + return isDistributionClientRunning; + } + + public void setIsDistributionClientRunning(boolean isDistributionClientRunning) { + this.isDistributionClientRunning = isDistributionClientRunning; + } + + public String getCatalogBePort() { + return catalogBePort; + } + + public String getDisributionClientHost() { + return disributionClientHost; + } + + public void setDisributionClientHost(String disributionClientHost) { + this.disributionClientHost = disributionClientHost; + } + + public String getDisributionClientPort() { + return disributionClientPort; + } + + public void setDisributionClientPort(String disributionClientPort) { + this.disributionClientPort = disributionClientPort; + } + + public void setCatalogBePort(String catalogBePort) { + this.catalogBePort = catalogBePort; + } + + public String getCatalogFeHost() { + return catalogFeHost; + } + + public void setCatalogFeHost(String catalogFeHost) { + this.catalogFeHost = catalogFeHost; + } + + public String getCatalogFePort() { + return catalogFePort; + } + + public void setCatalogFePort(String catalogFePort) { + this.catalogFePort = catalogFePort; + } + + public String getCatalogBeHost() { + return catalogBeHost; + } + + public void setCatalogBeHost(String catalogBeHost) { + this.catalogBeHost = catalogBeHost; + } + + public String getEsHost() { + return esHost; + } + + public void setEsHost(String esHost) { + this.esHost = esHost; + } + + public String getEsPort() { + return esPort; + } + + public void setEsPort(String esPort) { + this.esPort = esPort; + } + + public String getResourceConfigDir() { + return resourceConfigDir; + } + + public void setResourceConfigDir(String resourceConfigDir) { + this.resourceConfigDir = resourceConfigDir; + } + + public String getOutputFolder() { + return outputFolder; + } + + public void setOutputFolder(String outputFolder) { + this.outputFolder = outputFolder; + } + + public String getReportName() { + return reportName; + } + + public void setReportName(String reportName) { + this.reportName = reportName; + } + + public String getNeoPort() { + return neoPort; + } + + public void setNeoPort(String neoPort) { + this.neoPort = neoPort; + } + + public String getNeoHost() { + return neoHost; + } + + public void setNeoHost(String neoHost) { + this.neoHost = neoHost; + } + + public String getNeoDBpassword() { + return neoDBpassword; + } + + public String getNeoDBusername() { + return neoDBusername; + } + + public void setNeoDBusername(String neoDBusername) { + this.neoDBusername = neoDBusername; + } + + public void setNeoDBpassword(String neoDBpassword) { + this.neoDBpassword = neoDBpassword; + } + + public List<String> getPackages() { + return packages; + } + + public void setPackages(List<String> packages) { + this.packages = packages; + } + + public List<String> getBugs() { + return bugs; + } + + public void setBugs(List<String> bugs) { + this.bugs = bugs; + } + + public boolean isStopOnClassFailure() { + return stopOnClassFailure; + } + + public void setStopOnClassFailure(boolean stopOnClassFailure) { + this.stopOnClassFailure = stopOnClassFailure; + } + + public String getImportResourceConfigDir() { + return importResourceConfigDir; + } + + public void setImportResourceConfigDir(String importResourceConfigDir) { + this.importResourceConfigDir = importResourceConfigDir; + } + + public String getImportResourceTestsConfigDir() { + return importResourceTestsConfigDir; + } + + public void setImportResourceTestsConfigDir(String importResourceTestsConfigDir) { + this.importResourceTestsConfigDir = importResourceTestsConfigDir; + } + + public String getErrorConfigurationFile() { + return errorConfigurationFile; + } + + public void setErrorConfigurationFile(String errorConfigurationFile) { + this.errorConfigurationFile = errorConfigurationFile; + } + + public String getCatalogBeTlsPort() { + return catalogBeTlsPort; + } + + public void setCatalogBeTlsPort(String catalogBeTlsPort) { + this.catalogBeTlsPort = catalogBeTlsPort; + } + + public List<String> getResourcesNotToDelete() { + return resourcesNotToDelete; + } + + public void setResourcesNotToDelete(List<String> resourcesNotToDelete) { + this.resourcesNotToDelete = resourcesNotToDelete; + } + + public List<String> getResourceCategoriesNotToDelete() { + return resourceCategoriesNotToDelete; + } + + public void setResourceCategoriesNotToDelete(List<String> resourceCategoriesNotToDelete) { + this.resourceCategoriesNotToDelete = resourceCategoriesNotToDelete; + } + + public List<String> getServiceCategoriesNotToDelete() { + return serviceCategoriesNotToDelete; + } + + public void setServiceCategoriesNotToDelete(List<String> serviceCategoriesNotToDelete) { + this.serviceCategoriesNotToDelete = serviceCategoriesNotToDelete; + } + + public String getCassandraHost() { + return cassandraHost; + } + + public void setCassandraHost(String cassandraHost) { + this.cassandraHost = cassandraHost; + } + + public String getCassandraAuditKeySpace() { + return cassandraAuditKeySpace; + } + + public void setCassandraAuditKeySpace(String cassandraAuditKeySpace) { + this.cassandraAuditKeySpace = cassandraAuditKeySpace; + } + + public String getCassandraArtifactKeySpace() { + return cassandraArtifactKeySpace; + } + + public void setCassandraArtifactKeySpace(String cassandraArtifactKeySpace) { + this.cassandraArtifactKeySpace = cassandraArtifactKeySpace; + } + + public String getDownloadAutomationFolder() { + return downloadAutomationFolder; + } + + public void setDownloadAutomationFolder(String downloadAutomationFolder) { + this.downloadAutomationFolder = downloadAutomationFolder; + } + + @Override + public String toString() { + return "Config [systemUnderDebug=" + systemUnderDebug + ", rerun=" + rerun + ", reportDBhost=" + reportDBhost + + ", reportDBport=" + reportDBport + ", browser=" + browser + ", catalogBeHost=" + catalogBeHost + + ", esHost=" + esHost + ", esPort=" + esPort + ", neoHost=" + neoHost + ", neoPort=" + neoPort + + ", disributionClientHost=" + disributionClientHost + ", disributionClientPort=" + + disributionClientPort + ", isDistributionClientRunning=" + isDistributionClientRunning + + ", errorConfigurationFile=" + errorConfigurationFile + ", resourceConfigDir=" + resourceConfigDir + + ", importResourceConfigDir=" + importResourceConfigDir + ", importResourceTestsConfigDir=" + + importResourceTestsConfigDir + ", catalogFeHost=" + + catalogFeHost + ", catalogFePort=" + catalogFePort + ", catalogBePort=" + catalogBePort + + ", catalogBeTlsPort=" + catalogBeTlsPort + ", neoDBusername=" + neoDBusername + ", neoDBpassword=" + + neoDBpassword + ", packages=" + packages + ", bugs=" + + bugs + ", resourcesNotToDelete=" + resourcesNotToDelete + ", resourceCategoriesNotToDelete=" + + resourceCategoriesNotToDelete + ", serviceCategoriesNotToDelete=" + serviceCategoriesNotToDelete + + ", stopOnClassFailure=" + stopOnClassFailure + ", outputFolder=" + outputFolder + ", reportName=" + + reportName + ", url=" + url + ", remoteTestingMachineIP=" + remoteTestingMachineIP + + ", remoteTestingMachinePort=" + remoteTestingMachinePort + ", remoteTesting=" + remoteTesting + + ", cassandraHost=" + cassandraHost + ", cassandraAuditKeySpace=" + cassandraAuditKeySpace + + ", cassandraArtifactKeySpace=" + cassandraArtifactKeySpace + ", cassandraAuthenticate=" + + cassandraAuthenticate + ", cassandraUsername=" + cassandraUsername + ", cassandraPassword=" + + cassandraPassword + ", cassandraSsl=" + cassandraSsl + ", cassandraTruststorePath=" + + cassandraTruststorePath + ", cassandraTruststorePassword=" + cassandraTruststorePassword + + ", captureTraffic=" + captureTraffic + + ", useBrowserMobProxy=" + useBrowserMobProxy + ", configurationFile=" + configurationFile + + ", downloadAutomationFolder=" + downloadAutomationFolder + "]"; + } + + public boolean isRemoteTesting() { + return remoteTesting; + } + + public void setRemoteTesting(boolean remoteTesting) { + this.remoteTesting = remoteTesting; + } + + public String getUrl() { + try { + return url; + } catch (Exception e) { + return null; + } + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRemoteTestingMachineIP() { + return remoteTestingMachineIP; + } + + public void setRemoteTestingMachineIP(String remoteTestingMachineIP) { + this.remoteTestingMachineIP = remoteTestingMachineIP; + } + + public String getRemoteTestingMachinePort() { + return remoteTestingMachinePort; + } + + public void setRemoteTestingMachinePort(String remoteTestingMachinePort) { + this.remoteTestingMachinePort = remoteTestingMachinePort; + } + + public boolean getCassandraAuthenticate() { + return cassandraAuthenticate; + } + + public void setCassandraAuthenticate(boolean cassandraAuthenticate) { + this.cassandraAuthenticate = cassandraAuthenticate; + } + + public String getCassandraUsername() { + return cassandraUsername; + } + + public void setCassandraUsername(String cassandraUsername) { + this.cassandraUsername = cassandraUsername; + } + + public String getCassandraPassword() { + return cassandraPassword; + } + + public void setCassandraPassword(String cassandraPassword) { + this.cassandraPassword = cassandraPassword; + } + + public boolean getCassandraSsl() { + return cassandraSsl; + } + + public void setCassandraSsl(boolean cassandraSsl) { + this.cassandraSsl = cassandraSsl; + } + + public String getCassandraTruststorePath() { + return cassandraTruststorePath; + } + + public void setCassandraTruststorePath(String cassandraTruststorePath) { + this.cassandraTruststorePath = cassandraTruststorePath; + } + + public String getCassandraTruststorePassword() { + return cassandraTruststorePassword; + } + + public void setCassandraTruststorePassword(String cassandraTruststorePassword) { + this.cassandraTruststorePassword = cassandraTruststorePassword; + } } diff --git a/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/utils/Utils.java b/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/utils/Utils.java index 86d1ddb524..100d7f009a 100644 --- a/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/utils/Utils.java +++ b/integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/utils/Utils.java @@ -240,314 +240,7 @@ public final class Utils { } return config; } - // public void uploadNormativeTypes() throws IOException{ - // Config config = getConfig(); - // String[] normativeTypes = {"root", "compute", "blockStorage", - // "softwareComponent", "DBMS", "database", "network", "objectStorage", - // "webServer", "webApplication"}; - // for( String normativeType : normativeTypes ){ - // uploadComponent(config.getComponentsConfigDir()+File.separator+"normativeTypes"+File.separator+normativeType); - // } - // - // } - // - // public void uploadApacheComponent() throws IOException{ - // Config config = getConfig(); - // uploadComponent(config.getComponentsConfigDir()+File.separator+"apache"); - // } - // - // public void uploadComponent(String componentDir) throws IOException{ - // - // //*********************************************upload************************************************************* - // Config config = getConfig(); - // ZipDirectory zipDirectory = new ZipDirectory(); - // System.out.println(config.getEsHost()); - // - // List<UploadArtifactInfo> artifactsList = new - // ArrayList<UploadArtifactInfo>(); - // - //// read test resources and zip it as byte array - // byte[] zippedAsByteArray = zipDirectory.zip(componentDir, artifactsList); - // - //// encode zipped directory using base64 - // String payload = Decoder.encode(zippedAsByteArray); - // - //// zip name build as testName with ".zip" extension - // String payloadZipName = getPayloadZipName(componentDir); - // - //// build json - // UploadResourceInfo resourceInfo = new UploadResourceInfo(payload, - // payloadZipName, "description", "category/mycategory", null, - // artifactsList); - // String json = new Gson().toJson(resourceInfo); - // - //// calculate md5 on the content of json - // String jsonMd5 = - // org.apache.commons.codec.digest.DigestUtils.md5Hex(json); - // - //// encode the md5 to base64, sent as header in post http request - // String encodedMd5 = Decoder.encode(jsonMd5.getBytes()); - // - //// upload component to Elastic Search DB - // String url = null; - // HttpRequest http = new HttpRequest(); - // - // url = String.format(Urls.UPLOAD_ZIP_URL, config.getCatalogFeHost(), - // config.getCatalogFePort()); - // - //// Prepare headers to post upload component request - // HeaderData headerData = new HeaderData(encodedMd5, "application/json", - // "att", "test", "testIvanovich", "RoyalSeal", "Far_Far_Away", - // "getResourceArtifactListTest"); - // - // MustHeaders headers = new MustHeaders(headerData); - // System.out.println("headers:"+headers.getMap()); - // - // RestResponse response = http.httpSendPost(url, json, headers.getMap()); - // - // assertEquals("upload component failed with code " + - // response.getErrorCode().intValue(),response.getErrorCode().intValue(), - // 204); - // } - // - // private String getPayloadZipName(String componentDir) { - // String payloadName; - // if( componentDir.contains( File.separator) ){ - // String delimiter = null; - // if( File.separator.equals("\\")){ - // delimiter ="\\\\"; - // } - // else{ - // delimiter = File.separator; - // } - // String[] split = componentDir.split(delimiter); - // payloadName = split[split.length-1]; - // } - // else{ - // payloadName = componentDir; - // } - // return payloadName+".zip"; - // } - // - // - // - // public List<UploadArtifactInfo> createArtifactsList(String srcDir) { - // - // List<UploadArtifactInfo> artifactsList = new - // ArrayList<UploadArtifactInfo>(); - // File srcFile = new File(srcDir); - // addFileToList(srcFile, artifactsList); - // - // return artifactsList; - // } - // - // public void addFileToList(File srcFile, List<UploadArtifactInfo> - // artifactsList) { - // - // File[] files = srcFile.listFiles(); - // - // for (int i = 0; i < files.length; i++) { - // // if the file is directory, use recursion - // if (files[i].isDirectory()) { - // addFileToList(files[i], artifactsList); - // continue; - // } - // - // String fileName = files[i].getName(); - // String artifactPath = fileName; - // - // if ( ! files[i].getName().matches("(.*)\\.y(?)ml($)")) { - // UploadArtifactInfo uploadArtifactInfo = new UploadArtifactInfo(); - // uploadArtifactInfo.setArtifactName(files[i].getName()); - // String parent = files[i].getParent(); - // - // if (parent != null) { - // System.out.println(parent); - // int lastSepartor = parent.lastIndexOf(File.separator); - // if (lastSepartor > -1) { - // String actualParent = parent.substring(lastSepartor + 1); - // artifactPath = actualParent + "/" + artifactPath; - // } - // } - // - // uploadArtifactInfo.setArtifactPath(artifactPath); - // uploadArtifactInfo.setArtifactType(getFileTypeByExtension(fileName)); - // uploadArtifactInfo.setArtifactDescription("description"); - // artifactsList.add(uploadArtifactInfo); - // - // System.out.println("artifact list: " + artifactsList); - // - // } - // - // } - // } - // - // - // public String buildArtifactListUrl (String nodesType, String - // templateVersion, String artifactName) throws FileNotFoundException{ - // //"http://172.20.43.132/sdc2/v1/catalog/resources/tosca.nodes.Root/1.0.0.wd03-SNAPSHOT/artifacts/wxs_baseline_compare.sh" - // Config config = getConfig(); - // return "\"http://" + config.getCatalogBeHost() + ":" + - // config.getCatalogBePort() + "/sdc2/v1/catalog/resources/" +nodesType + - // "/" + templateVersion + "/artifacts/" + artifactName +"\""; - // } - // - // - // public void addTopologyToES(String testFolder, String - // serviceTopologyPattern) throws IOException{ - // Config config = getConfig(); - // String url = String.format(Urls.ES_URL, config.getEsHost(), - // config.getEsPort()) + serviceTopologyPattern; - // String sourceDir = - // config.getResourceConfigDir()+File.separator+testFolder; - // Path filePath = FileSystems.getDefault().getPath(sourceDir, - // "topology.txt"); - // postFileContentsToUrl(url, filePath); - // } - // - // public void addTopologyTemplateToES(String testFolder, String - // serviceTopologyTemplatePattern) throws IOException{ - // Config config = getConfig(); - // String url = String.format(Urls.ES_URL, config.getEsHost(), - // config.getEsPort()) + serviceTopologyTemplatePattern; - // String sourceDir = - // config.getResourceConfigDir()+File.separator+testFolder; - // Path filePath = FileSystems.getDefault().getPath(sourceDir, - // "topologyTemplate.txt"); - // postFileContentsToUrl(url, filePath); - // } - // - // - // public void postFileContentsToUrl(String url, Path filePath) throws - // IOException { - // HttpClientContext localContext = HttpClientContext.create(); - // CloseableHttpResponse response = null; - // - // byte[] fileContent = Files.readAllBytes(filePath); - // - // try(CloseableHttpClient httpClient = HttpClients.createDefault()){ - // HttpPost httpPost = new HttpPost(url); - // StringEntity entity = new StringEntity(new String(fileContent) , - // ContentType.APPLICATION_JSON); - // httpPost.setEntity(entity); - // response = httpClient.execute(httpPost, localContext); - // - // } - // finally{ - // response.close(); - // } - // - // - // } - // - // - //// public boolean isPatternInEsDb(String patternToSearch)throws - // IOException{ - //// Config config = getConfig(); - //// String url = String.format(Urls.GET_SEARCH_DATA_FROM_ES, - // config.getEsHost(), config.getEsPort(),patternToSearch); - //// HttpRequest httpRequest = new HttpRequest(); - //// RestResponse restResponse = httpRequest.httpSendGet(url); - //// if (restResponse.getErrorCode() == 200){ - //// return true; - //// } - //// if (restResponse.getErrorCode() == 404){ - //// return false; - //// } - //// - //// return false; - //// } - // - // public static RestResponse deleteAllDataFromEs() throws IOException{ - // return deleteFromEsDbByPattern("_all"); - // } - // - // - // public List<String> buildIdArrayListByTypesIndex (String index, String - // types) throws IOException{ - // - // Config config = getConfig(); - // HttpRequest http = new HttpRequest(); - // RestResponse getResponce = - // http.httpSendGet(String.format(Urls.GET_ID_LIST_BY_INDEX_FROM_ES, - // config.getEsHost(), config.getEsPort(), index, types), null); - // - // List <String> idArray = new ArrayList<String>(); - // - // JsonElement jelement = new JsonParser().parse(getResponce.getResponse()); - // JsonObject jobject = jelement.getAsJsonObject(); - // JsonObject hitsObject = (JsonObject) jobject.get("hits"); - // JsonArray hitsArray = (JsonArray) hitsObject.get("hits"); - // for (int i = 0; i < hitsArray.size(); i ++){ - // JsonObject idObject = (JsonObject) hitsArray.get(i); - // String id = idObject.get("_id").toString(); - // id = id.replace("\"", ""); - // idArray.add(id); - // } - // - // return idArray; - // } - // - // public List<String> buildCategoriesTagsListFromJson(String - // categoriesTagsJson){ - // - // ArrayList<String> categoriesTagsArray = new ArrayList<>(); - // JsonElement jelement = new JsonParser().parse(categoriesTagsJson); - // JsonArray jArray = jelement.getAsJsonArray(); - // for (int i = 0; i < jArray.size(); i ++){ - // JsonObject categoriesTagsObject = (JsonObject) jArray.get(i); - // String categories = categoriesTagsObject.get("name").toString(); - // categoriesTagsArray.add(categories); - // } - // - // return categoriesTagsArray; - // } - // - // public ArrayList <String> getCategoriesFromDb() throws Exception{ - // - // ArrayList<String> categoriesFromDbArrayList = new ArrayList<>(); - // RestResponse restResponse = new RestResponse(); - // String contentTypeHeaderData = "application/json"; - // String acceptHeaderDate = "application/json"; - // - // Map<String, String> headersMap = new HashMap<String,String>(); - // headersMap.put(HttpHeaderEnum.CONTENT_TYPE.getValue(),contentTypeHeaderData); - // headersMap.put(HttpHeaderEnum.ACCEPT.getValue(), acceptHeaderDate); - // - // HttpRequest httpRequest = new HttpRequest(); - // String url = String.format(Urls.QUERY_NEO4J, - // Config.instance().getNeoHost(), Config.instance().getNeoPort()); - // String body = "{\"statements\" : [ { \"statement\" : \"MATCH - // (category:category) return (category)\"} ]}"; - // restResponse = httpRequest.httpSendPostWithAuth(url, body, headersMap, - // Config.instance().getNeoDBusername(), - // Config.instance().getNeoDBpassword()); - // - // if (restResponse.getResponse()==null){ - // return categoriesFromDbArrayList; - // }else{ - // JsonElement jelement = new - // JsonParser().parse(restResponse.getResponse()); - // JsonObject jobject = jelement.getAsJsonObject(); - // JsonArray resultsArray = (JsonArray) jobject.get("results"); - // JsonObject resObject = (JsonObject) resultsArray.get(0); - // JsonArray dataArray = (JsonArray) resObject.get("data"); - // for (int i = 0; i < dataArray.size(); i ++){ - // JsonObject rowObject = (JsonObject) dataArray.get(i); - // JsonArray rowArray = (JsonArray) rowObject.get("row"); - // JsonObject nameObject = (JsonObject) rowArray.get(0); - // String name = nameObject.get("name").toString(); - //// name = name.replace("\"", ""); - // categoriesFromDbArrayList.add(name); - // } - // - // - // } - // - // return categoriesFromDbArrayList; - // } - // public static void compareArrayLists(List<String> actualArraylList, List<String> expectedArrayList, String message) { @@ -636,38 +329,6 @@ public final class Utils { return listOfToscaArtTypesFromConfig; } - // - // public static List<String> getListOfResDepArtTypes() throws - // FileNotFoundException { - // - // List<String> listOfResDepArtTypesFromConfig = new ArrayList<String>(); - // @SuppressWarnings("unchecked") - // Map<String, Object> resourceDeploymentArtifacts = (Map<String, Object>) - // parseYamlConfig("resourceDeploymentArtifacts"); - // for (Map.Entry<String, Object> iter : - // resourceDeploymentArtifacts.entrySet()) { - // listOfResDepArtTypesFromConfig.add(iter.getKey()); - // } - // - // return listOfResDepArtTypesFromConfig; - // } - // - // public static List<String> getListOfDepResInstArtTypes() throws - // FileNotFoundException { - // - // List<String> listOfResInstDepArtTypesFromConfig = new - // ArrayList<String>(); - // @SuppressWarnings("unchecked") - // Map<String, Object> resourceDeploymentArtifacts = (Map<String, Object>) - // parseYamlConfig("deploymentResourceInstanceArtifacts"); - // for (Map.Entry<String, Object> iter : - // resourceDeploymentArtifacts.entrySet()) { - // listOfResInstDepArtTypesFromConfig.add(iter.getKey().toLowerCase()); - // } - // - // return listOfResInstDepArtTypesFromConfig; - // } - // public static List<String> getListOfResPlaceHoldersDepArtTypes() throws FileNotFoundException { List<String> listResDepArtTypesFromConfig = new ArrayList<String>(); List<String> listOfResDepArtLabelsFromConfig = getListOfDepResArtLabels(false); diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/AddComponentInstancesArtifactsInCsar.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/AddComponentInstancesArtifactsInCsar.java new file mode 100644 index 0000000000..439cfa67a7 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/AddComponentInstancesArtifactsInCsar.java @@ -0,0 +1,340 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.http.HttpStatus; +import org.onap.sdc.backend.ci.tests.datatypes.ArtifactReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.ToscaArtifactsPage; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.backend.ci.tests.execute.devCI.ArtifactFromCsar; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ArtifactRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class AddComponentInstancesArtifactsInCsar extends SetupCDTest { + + public static final String DEPLOYMENT = "Deployment"; + public static final String INFORMATIONAL = "Informational"; + private String filePath; + + @BeforeClass + public void beforeClass() { + filePath = System.getProperty("filePath"); + if (filePath == null && System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getResourcesFilesPath() + "AddComponentInstancesArtifactsInCsar" + File.separator; + } else if (filePath.isEmpty() && !System.getProperty("os.name").contains("Windows")) { + filePath = FileHandling.getBasePath() + File.separator + "src/test/resources/Files" + File.separator + "AddComponentInstancesArtifactsInCsar" + File.separator; + } + } + + // US847439 - Story [BE] - Add Component Instance's artifacts in CSAR + // TC1521795 - VF CSAR - The Flow + @Test + public void vfAndServiceCsarTheFlow() throws Exception { + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "FDNT.zip"; + String snmpFile = "Fault-alarms-ASDC-vprobes-vLB.zip"; + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject createVSP = VendorSoftwareProductRestUtils.createVSP(resourceReqDetails, vnfFile, filePath, getUser(), + vendorLicenseModel); + String vspName = createVSP.getName(); + resourceMetaData.setName(vspName); + VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpFile, null, createVSP, getUser()); + VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), createVSP, true); + + HomePage.showVspRepository(); + OnboardingUiUtils.importVSP(createVSP); + resourceMetaData.setVersion("0.1"); + Resource vfResource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), resourceMetaData.getVersion()); + + Map<String, Object> artifacts = getArtifactsOfComponentAndComponentsInstance(vfResource); + + List<ImmutablePair<ComponentInstance, ArtifactDefinition>> artifactsUploadedToComponentInstance = new LinkedList<>(); + Random random = new Random(); + final int randomIntForLoop = random.nextInt(10) + 10; + for (int i = 0; i < randomIntForLoop; i++) { + ImmutablePair<ComponentInstance, ArtifactDefinition> uploadArtifactOnRandomVfc = uploadArtifactOnRandomRI(vfResource); + + if (uploadArtifactOnRandomVfc.getRight().getArtifactName() != null) { + artifactsUploadedToComponentInstance.add(uploadArtifactOnRandomVfc); + } + } + + if (!artifactsUploadedToComponentInstance.isEmpty()) { + Map<String, Object> artifactsOfResourceInstance = getArtifactsOfResourceInstance(artifactsUploadedToComponentInstance); + artifacts.put("Resources", artifactsOfResourceInstance); + } + + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + ToscaArtifactsPage.downloadCsar(); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + Map<String, Object> combineHeatArtifacstWithFolderArtifacsToMap = ArtifactFromCsar.getVFCArtifacts(latestFilefromDir.getAbsolutePath()); + + compareArtifactFromFileStructureToArtifactsFromJavaObject(artifacts, combineHeatArtifacstWithFolderArtifacsToMap); + + } + + public void compareArtifactFromFileStructureToArtifactsFromJavaObject(Map<String, Object> artifactFromJavaObject, Map<String, Object> artifactsFromFileStructure) { + for (String key : artifactFromJavaObject.keySet()) { + if ((!key.equals(DEPLOYMENT)) && (!key.equals(INFORMATIONAL))) { + Map<String, Object> newArtifactFromJavaObject = (Map<String, Object>) artifactFromJavaObject.get(key); + Map<String, Object> newArtifactsFromFileStructure = (Map<String, Object>) artifactsFromFileStructure.get(key); + compareArtifactFromFileStructureToArtifactsFromJavaObject(newArtifactFromJavaObject, newArtifactsFromFileStructure); + } else { + compareArtifacts(artifactFromJavaObject.get(key), artifactsFromFileStructure.get(key)); + } + } + } + + + private void compareArtifacts(Object artifactFromJavaObject, Object artifactsFromFileStructure) { + Map<String, List<String>> artifactsMap = (Map<String, List<String>>) artifactFromJavaObject; + List<HeatMetaFirstLevelDefinition> artifactsList = (List<HeatMetaFirstLevelDefinition>) artifactsFromFileStructure; + + for (HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition : artifactsList) { + Assert.assertTrue(artifactsMap.get(heatMetaFirstLevelDefinition.getType()).contains(heatMetaFirstLevelDefinition.getFileName()), + "Expected that artifacts will be the same. Not exists: " + heatMetaFirstLevelDefinition.getFileName() + " of type: " + heatMetaFirstLevelDefinition.getType()); + } + + for (String key : artifactsMap.keySet()) { + List<String> artifacts = artifactsMap.get(key); + + for (HeatMetaFirstLevelDefinition heatMetaFirstLevelDefinition : artifactsList) { + if (heatMetaFirstLevelDefinition.getType().equals(key)) { + if (artifacts.contains(heatMetaFirstLevelDefinition.getFileName())) { + artifacts.remove(heatMetaFirstLevelDefinition.getFileName()); + } + } + } + + Assert.assertEquals(artifacts.size(), 0, "Expected that all artifacts equal. There is artifacts which not equal: " + artifacts.toString()); + } + } + + + public Map<String, Object> getArtifactsOfResourceInstance(List<ImmutablePair<ComponentInstance, ArtifactDefinition>> riList) { + Map<String, Object> artifacts = new HashMap<>(); + + for (ImmutablePair<ComponentInstance, ArtifactDefinition> ri : riList) { + ArtifactDefinition artifactDefinition = ri.getRight(); + ComponentInstance componentInstance = ri.getLeft(); + if (artifacts.containsKey(componentInstance.getNormalizedName())) { + if (((Map<String, ArrayList<String>>) ((Map<String, Object>) artifacts.get(componentInstance.getNormalizedName())).get(DEPLOYMENT)).containsKey(artifactDefinition.getArtifactType())) { + + ((Map<String, ArrayList<String>>) ((Map<String, Object>) artifacts.get(componentInstance.getNormalizedName())).get(DEPLOYMENT)).get(artifactDefinition.getArtifactType()).add(artifactDefinition.getArtifactName()); + + } else { + ArrayList<String> list = new ArrayList<>(); + list.add(artifactDefinition.getArtifactName()); + ((Map<String, ArrayList<String>>) ((Map<String, Object>) artifacts.get(componentInstance.getNormalizedName())).get(DEPLOYMENT)).put(artifactDefinition.getArtifactType(), list); + } + + } else { + try { + + + ArrayList<String> list = new ArrayList<>(); + list.add(artifactDefinition.getArtifactName()); + + Map<String, ArrayList<String>> map = new HashMap<>(); + map.put(artifactDefinition.getArtifactType(), list); + + Map<String, Map<String, ArrayList<String>>> addMap = new HashMap<>(); + addMap.put(DEPLOYMENT, map); + + artifacts.put(componentInstance.getNormalizedName(), addMap); + } catch (Exception e) { + Assert.fail("Artifact name is null for componentInstance: " + componentInstance.getNormalizedName()); + } + } + } + return artifacts; + } + + public Map<String, Object> getArtifactsOfComponentAndComponentsInstance(Component component) { + Map<String, Object> artifacts = getArtifactsOfComponent(component); + + for (ComponentInstance componentInstance : component.getComponentInstances()) { + Map<String, Object> artifactsOfComponentInstance = getArtifactsOfComponentInstance(componentInstance); + if (!artifactsOfComponentInstance.isEmpty()) { + artifacts.put(componentInstance.getToscaComponentName() + "." + componentInstance.getComponentVersion(), artifactsOfComponentInstance); + } + } + + return artifacts; + } + + public Map<String, Object> getArtifactsOfComponentInstance(ComponentInstance componentInstance) { + Map<String, Object> map = new HashMap<>(); + + if (componentInstance.getArtifacts() != null) { + Map<String, Object> informationalArtifacts = getArtifacts(componentInstance.getArtifacts()); + if (!informationalArtifacts.isEmpty()) { + map.put(INFORMATIONAL, informationalArtifacts); + } + } + + if (componentInstance.getDeploymentArtifacts() != null) { + Map<String, Object> deploymentArtifacts = getArtifacts(componentInstance.getDeploymentArtifacts()); + if (!deploymentArtifacts.isEmpty()) { + map.put(DEPLOYMENT, deploymentArtifacts); + } + } + + return map; + } + + public Map<String, Object> getArtifactsOfComponent(Component component) { + Map<String, Object> map = new HashMap<>(); + + if (component.getArtifacts() != null) { + Map<String, Object> informationalArtifacts = getArtifacts(component.getArtifacts()); + if (!informationalArtifacts.isEmpty()) { + map.put(INFORMATIONAL, informationalArtifacts); + } + } + + if (component.getDeploymentArtifacts() != null) { + Map<String, Object> deploymentArtifacts = getArtifacts(component.getDeploymentArtifacts()); + if (!deploymentArtifacts.isEmpty()) { + map.put(DEPLOYMENT, deploymentArtifacts); + } + } + + return map; + } + + public Map<String, Object> getArtifacts(Map<String, ArtifactDefinition> artifacts) { + Map<String, Object> map = new HashMap<>(); + + for (String artifact : artifacts.keySet()) { + ArtifactDefinition artifactDefinition = artifacts.get(artifact); + if ((artifactDefinition.getEsId() != null) && (!artifactDefinition.getEsId().equals("")) && (!artifactDefinition.getArtifactType().equals("HEAT_ENV"))) { + if (map.containsKey(artifactDefinition.getArtifactType())) { + ((List<String>) map.get(artifactDefinition.getArtifactType())).add(artifactDefinition.getArtifactName()); + } else { + ArrayList<String> list = new ArrayList<>(); + list.add(artifactDefinition.getArtifactName()); + map.put(artifactDefinition.getArtifactType(), list); + } + } + } + + return map; + } + + public ImmutablePair<ComponentInstance, ArtifactDefinition> uploadArtifactOnRandomRI(Component component) throws Exception { + ArtifactReqDetails artifactReqDetails = getRandomArtifact(); + Random random = new Random(); + int randInt = random.nextInt(component.getComponentInstances().size()); + User defaultUser = ElementFactory.getDefaultUser(getRole()); + ComponentInstance componentInstance = component.getComponentInstances().get(randInt); + + RestResponse uploadArtifactRestResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(component, defaultUser, artifactReqDetails, componentInstance); + + // Check response of external API + Integer responseCode = uploadArtifactRestResponse.getErrorCode(); + Assert.assertEquals(responseCode, (Integer) HttpStatus.SC_OK, "Response code is not correct."); + + ImmutablePair<ComponentInstance, ArtifactDefinition> pair = ImmutablePair.of(componentInstance, ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactRestResponse.getResponse())); + + return pair; + } + + public ImmutablePair<ComponentInstance, ArtifactDefinition> uploadArtifactOnRandomRI(Resource resource) throws Exception { + ArtifactReqDetails artifactReqDetails = getRandomVfcArtifact(); + Random random = new Random(); + int randInt = random.nextInt(resource.getComponentInstances().size()); + User defaultUser = ElementFactory.getDefaultUser(getRole()); + ComponentInstance componentInstance = resource.getComponentInstances().get(randInt); + + RestResponse uploadArtifactRestResponse = ArtifactRestUtils.externalAPIUploadArtifactOfComponentInstanceOnAsset(resource, defaultUser, artifactReqDetails, componentInstance); + // Check response of external API + Integer responseCode = uploadArtifactRestResponse.getErrorCode(); + Assert.assertEquals(responseCode, (Integer) HttpStatus.SC_OK, "Response code is not correct."); + ImmutablePair<ComponentInstance, ArtifactDefinition> pair = ImmutablePair.of(componentInstance, ResponseParser.convertArtifactDefinitionResponseToJavaObject(uploadArtifactRestResponse.getResponse())); + return pair; + } + + public ArtifactReqDetails getRandomArtifact() throws Exception { + List<String> artifactsTypeList = Arrays.asList("Other"); + return getRandomArtifact(artifactsTypeList); + } + + public ArtifactReqDetails getRandomVfcArtifact() throws Exception { + List<String> vfcArtifactsTypeList = Arrays.asList( + ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType(), + ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType(), + ArtifactTypeEnum.DCAE_INVENTORY_POLICY.getType(), + ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType(), + ArtifactTypeEnum.DCAE_INVENTORY_BLUEPRINT.getType(), + ArtifactTypeEnum.DCAE_INVENTORY_EVENT.getType(), + ArtifactTypeEnum.SNMP_POLL.getType(), + ArtifactTypeEnum.SNMP_TRAP.getType()); + return getRandomArtifact(vfcArtifactsTypeList); + } + + public ArtifactReqDetails getRandomArtifact(List<String> artifactType) throws Exception { + Random random = new Random(); + return ElementFactory.getArtifactByType("ci", artifactType.get(random.nextInt(artifactType.size())), true, false); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java new file mode 100644 index 0000000000..11a3a8e062 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/ImportUpdateInformationalDeploymentArtifacts.java @@ -0,0 +1,227 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.testng.AssertJUnit.assertTrue; + +public class ImportUpdateInformationalDeploymentArtifacts extends SetupCDTest { + + private String folder = "US747946"; + + // US747946 - Import artifacts to component instances + // TC1407822 - Import VFC Artifacts - Deployment Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfvArtifactsDeploymentArtifactsMultipleArtifactsMultipleTypes() throws Exception { + + String filePath = FileHandling.getFilePath(folder); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String fileName = "TC1407822.csar"; + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + List<String> snmpPollArtifactList = Stream + .of("base_cgi_frwl.mib", "base_vIECCF_volume.yml", "node_userdata_script.sh", "vendor-license-model.xml") + .collect(Collectors.toList()); + List<String> snmpTrapArtifactList = Stream + .of("module_1_ixlt.mib", "module_1_ixlt.yaml") + .collect(Collectors.toList()); + + + List<ArtifactDefinition> filteredArtifactNames = + //Stream of component Instances + resource.getComponentInstances().stream() + //filter out all nulls + .filter(e -> e.getDeploymentArtifacts() != null) + //Stream of all the artifacts on all the component instances + .flatMap(e -> e.getDeploymentArtifacts().values().stream()) + //filter relevant artifact types + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.SNMP_TRAP.getType()) || e.getArtifactType().equals(ArtifactTypeEnum.SNMP_POLL.getType())) + //collect to list + .collect(Collectors.toList()); + + assertTrue("Not contain all SNMP TRAP artifacts.", filteredArtifactNames.stream() + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.SNMP_TRAP.getType())) + .map(e -> e.getArtifactName()) + .collect(Collectors.toList()) + .containsAll(snmpTrapArtifactList)); + + assertTrue("Not contain all SNMP POLL artifacts.", filteredArtifactNames.stream() + .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.SNMP_POLL.getType())) + .map(e -> e.getArtifactName()) + .collect(Collectors.toList()) + .containsAll(snmpPollArtifactList)); + + filteredArtifactNames.stream() + .map(e -> e.getArtifactDisplayName()) + .collect(Collectors.toList()) + .forEach(e -> { + assertTrue("Wrong artifact appear on deployment artifact UI page.", + !GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + e)); + }); + + } + + // TODO: Note there is performance issue with this CSAR + // US747946 - Import artifacts to component instances + // TC1407998 - Import VFC Artifacts - Deployment & Informational Artifacts - Multiple VFCs + @Test + public void importVfcArtifactsDeploymentAndInformationalArtifactsMultipleVfcs() throws Exception { + + String filePath = FileHandling.getFilePath(folder); + String fileName = "TC1407998.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + resource.getComponentInstances().forEach(e -> { + + if (e.getToscaComponentName().endsWith("heat.cm")) { + Map<String, List<String>> deployArtifactsMap = new HashMap<String, List<String>>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("PS_DEPL_Poll1.mib", "PS_DEPL_Poll2.xml", "PS_DEPL_Poll3.yaml")); + put(ArtifactTypeEnum.SNMP_TRAP.getType(), Arrays.asList("PS_DEPL_Trap1.mib", "PS_DEPL_Trap2.xml", "PS_DEPL_Trap3.sh", "PS_DEPL_Trap4.yml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.cm"); + + } else if (e.getToscaComponentName().endsWith("heat.sm")) { + Map<String, List<String>> deployArtifactsMap = new HashMap<String, List<String>>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("SM_DEPL_Poll1.mib", "SM_DEPL_Poll2.mib", "SM_DEPL_Poll3.xml")); + put(ArtifactTypeEnum.SNMP_TRAP.getType(), Arrays.asList("SM_DEPL_Trap1.mib", "SM_DEPL_Trap2.xml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.sm"); + } + }); + + } + + // US747946 - Import artifacts to component instances + // TC1410352 - Import VFC Artifacts - Deployment Artifacts - Extra folder Under VFC-Identification + @Test + public void importVfcArtifactsDeploymentArtifactsExtraFolderUnderVfcIdentification() throws Exception { + + String filePath = FileHandling.getFilePath(folder); + String fileName = "TC1410352.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + resource.getComponentInstances().forEach(e -> { + + if (e.getToscaComponentName().endsWith("heat.ltm")) { + Map<String, List<String>> deployArtifactsMap = new HashMap<String, List<String>>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("Poll1.mib", "Poll2.xml", "Poll3.sh", "Poll4.yml")); + put(ArtifactTypeEnum.SNMP_TRAP.getType(), Arrays.asList("Trap1.mib", "Trap2.yaml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.ltm"); + } + }); + } + + + // US747946 - Import artifacts to component instances + // TC1410352 - Import VFC Artifacts - Deployment Artifacts - Invalid Artifact Type + @Test + public void importVfcArtifactsDeploymentArtifactsInvalidArtifactType() throws Exception { + + String filePath = FileHandling.getFilePath(folder); + String fileName = "TC1425032.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + resource.getComponentInstances().forEach(e -> { + + if (e.getToscaComponentName().endsWith("heat.ltm")) { + Map<String, List<String>> deployArtifactsMap = new HashMap<String, List<String>>() { + { + put(ArtifactTypeEnum.SNMP_POLL.getType(), Arrays.asList("DeploySNMPPoll1.mib", "DeploySNMPPoll2.yml", "DeploySNMPPoll3.sh", "DeploySNMPPoll4.xml")); + put(ArtifactTypeEnum.OTHER.getType(), Arrays.asList("DeploySNMPTrapB1.mib", "DeploySNMPTrapB2.yaml")); + } + }; + validateDeploymentArtifactOnComponetInstance(e, deployArtifactsMap, "heat.ltm"); + } + }); + } + + private void validateDeploymentArtifactOnComponetInstance(ComponentInstance instance, Map<String, List<String>> artifactsMap, String endswith) { + if (instance.getToscaComponentName().endsWith(endswith)) { + Set<String> types = artifactsMap.keySet(); + + Map<String, List<ArtifactDefinition>> collect = instance.getDeploymentArtifacts().values().stream() + .filter(a -> types.contains(a.getArtifactType())) + .collect(Collectors.groupingBy(e -> e.getArtifactType())); + + types.forEach(m -> { + if (collect.containsKey(m)) { + List<String> found = collect.get(m).stream().map(e -> e.getArtifactName()).collect(Collectors.toList()); + boolean isValid = found.containsAll(artifactsMap.get(m)) && artifactsMap.get(m).containsAll(found); + assertTrue("Not contain all artifact of type: " + m, isValid); + } else { + assertTrue("Contains deployment artifact which not in provided list", false); + } + }); + } + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/Inputs.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/Inputs.java new file mode 100644 index 0000000000..f340043eb5 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/Inputs.java @@ -0,0 +1,214 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.InputsPage; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.PropertyPopup; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.TestException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class Inputs extends SetupCDTest { + + private static final String DESCRIPTION = "kuku"; + private static final String ARTIFACT_LABEL = "artifact3"; + private static final String ARTIFACT_LABEL_UPDATE = "artifactUpdate"; + private static final String GET_ARTIFACT_LIST_BY_CLASS_NAME = "i-sdc-designer-sidebar-section-content-item-artifact"; + private static final String HEAT_FILE_YAML_NAME = "Heat-File.yaml"; + private static final String HEAT_FILE_YAML_UPDATE_NAME = "Heat-File-Update.yaml"; + private String filePath; + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath(""); + } + + // TODO: There is defect that imported VFC checkin not appear in service until refresh + // TODO: add support for CP (there is no normative CP's with complex properties which can be selected - import one) - importVFCWithComplexProperty.yml + // TC1508249 + // Delete Input declared from VLi/CPi in service level - Deleting an Input that was declared from Complex property. + @Test + public void deletingAnInputThatWasDeclaredFromComplexProperty() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + Map<String, List<String>> resourceInstanceToProperty = new HashMap<>(); + CompositionPage.searchForElement("ExtVL"); + CanvasElement computeElement = canvasManager.createElementOnCanvas("ExtVL"); + canvasManager.clickOnCanvaElement(computeElement); + resourceInstanceToProperty.put(CompositionPage.getSelectedInstanceName(), Arrays.asList("network_homing", "instance_node_target")); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToInputsScreen(); + + + for (String element : resourceInstanceToProperty.keySet()) { + String propertyName = resourceInstanceToProperty.get(element).get(0); + String innerPropertyName = resourceInstanceToProperty.get(element).get(1); + String dataTestIdPropertyCheckbox = DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + propertyName; + + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + + InputsPage.clickOnProperty(propertyName); + + PropertyPopup propertyPopup = new PropertyPopup(); + propertyPopup.selectPropertyRadioButton(innerPropertyName); + propertyPopup.clickSave(); + + InputsPage.clickOnAddInputButton(); + + // Verify that input checkbox selected + verifyPropertyCheckBoxSelected(dataTestIdPropertyCheckbox); + + InputsPage.deleteServiceInput(element, propertyName + "_" + innerPropertyName); + + // Trying to find deleted service input + try { + InputsPage.getServiceInput(element, propertyName + "_" + innerPropertyName); + assert false; + } catch (TestException e) { + System.out.println("Verfied that service input deleted"); + } + + // Verify that input checkbox not selected + verifyPropertyCheckBoxNotSelected(dataTestIdPropertyCheckbox); + + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + } + + } + + + // TC1508248 + // Delete inputs who come from CP/VL properties + @Test + public void deleteInputsWhoComeFromCpVlProperties() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + Map<String, String> resourceInstanceToProperty = new HashMap<>(); + CompositionPage.searchForElement("ExtVL"); + CanvasElement computeElement = canvasManager.createElementOnCanvas("ExtVL"); + canvasManager.clickOnCanvaElement(computeElement); + resourceInstanceToProperty.put(CompositionPage.getSelectedInstanceName(), "network_role"); + + CompositionPage.searchForElement("ExtCP"); + computeElement = canvasManager.createElementOnCanvas("ExtCP"); + canvasManager.clickOnCanvaElement(computeElement); + resourceInstanceToProperty.put(CompositionPage.getSelectedInstanceName(), "order"); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToInputsScreen(); + + + for (String element : resourceInstanceToProperty.keySet()) { + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + + WebElement webElementByTestID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + resourceInstanceToProperty.get(element)); + InputsPage.clickOnVFInputCheckbox(webElementByTestID); + + InputsPage.clickOnAddInputButton(); + + // Verify that input checkbox selected + verifyPropertyCheckBoxSelected(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + resourceInstanceToProperty.get(element)); + + InputsPage.deleteServiceInput(element, resourceInstanceToProperty.get(element)); + + // Trying to find deleted service input + try { + InputsPage.getServiceInput(element, resourceInstanceToProperty.get(element)); + assert false; + } catch (TestException e) { + System.out.println("Verfied that service input deleted"); + } + + // Verify that input checkbox not selected + verifyPropertyCheckBoxNotSelected(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_CHECKBOX.getValue() + resourceInstanceToProperty.get(element)); + + GeneralUIUtils.clickOnElementByText(element); + GeneralUIUtils.ultimateWait(); + } + + } + + + public String verifyPropertyCheckBox(String dataTestId) { + WebElement webElementByTestID = GeneralUIUtils.getWebElementByTestID(dataTestId); + webElementByTestID = webElementByTestID.findElement(By.className("tlv-checkbox-i")); + if (webElementByTestID.getAttribute("checked") == null) { + return "false"; + } + return "true"; + } + + public void verifyPropertyCheckBoxSelected(String dataTestId) { + if (!verifyPropertyCheckBox(dataTestId).equals("true")) { + Assert.assertEquals(true, false, "Expected that checkbox will be selected."); + } + } + + public void verifyPropertyCheckBoxNotSelected(String dataTestId) { + if (!verifyPropertyCheckBox(dataTestId).equals("false")) { + Assert.assertEquals(false, true, "Expected that checkbox will not be selected."); + } + } + + public String getNormalizedName(String notNormalizedName) { + String normalizedName = notNormalizedName.toLowerCase(); + normalizedName = normalizedName.replaceAll(" ", ""); + + return normalizedName; + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/MIBsArtifactsOnResourceInstance.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/MIBsArtifactsOnResourceInstance.java new file mode 100644 index 0000000000..f2b743a5a8 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/MIBsArtifactsOnResourceInstance.java @@ -0,0 +1,267 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import org.apache.commons.io.FileUtils; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.UploadArtifactPopup; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ArtifactRestUtils; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static org.testng.AssertJUnit.assertTrue; + + +public class MIBsArtifactsOnResourceInstance extends SetupCDTest { + + private String folder = ""; + + @DataProvider(name = "mibsArtifactCRUDUi") + public static Object[][] dataProviderMibsArtifactCRUDUi() { + return new Object[][]{ + {"mibsvFW_VFC.yml", ResourceTypeEnum.VFC}, + {"mibsVL.yml", ResourceTypeEnum.VL}, + {"mibsCP.yml", ResourceTypeEnum.CP} + }; + } + + // US820414 + // Artifact UI CRUD on VFC/VL/CP + // TODO: Change download validation from download artifact via external API to UI + @Test(dataProvider = "mibsArtifactCRUDUi") + public void mibsArtifactCRUDUi(String fileName, ResourceTypeEnum resourceTypeEnum) throws Exception { + setLog(fileName); + String filePath = FileHandling.getFilePath(folder); + + // import Resource + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser()); + ResourceUIUtils.importVfc(resourceMetaData, filePath, fileName, getUser()); + + // get resourceUUID from BE + String resourceUUID = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1").getUUID(); + + // 2. Upload MIBs artifacts - SNMP_TRAP & SNMP_POLL. + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "SNMP_TRAP")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "SNMP_POLL")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true)); + + assertTrue("Only created artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + + String artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + deploymentArtifact.getArtifactLabel()).getText(); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(deploymentArtifact.getArtifactLabel(), null, "1", deploymentArtifact.getArtifactType(), true, true, true, false); + + // Verify that uploaded correct file by download artifact via external api + RestResponse restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE.toString()); + File file = new File(deploymentArtifact.getFilepath() + deploymentArtifact.getFilename()); + + String readFileToString = FileUtils.readFileToString(file); + Assert.assertEquals(restResponse.getResponse(), readFileToString); + + DeploymentArtifactPage.clickEditArtifact(deploymentArtifact.getArtifactLabel()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filePath, "CP.yml"); + artifactPopup.clickDoneButton(); + + assertTrue("Only updated artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + Assert.assertNotEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + deploymentArtifact.getArtifactLabel()).getText(), artifactUUID); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(deploymentArtifact.getArtifactLabel(), null, "2", deploymentArtifact.getArtifactType(), true, true, true, false); + + // Verify that updated correct file by download artifact via external api + artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + deploymentArtifact.getArtifactLabel()).getText(); + restResponse = ArtifactRestUtils.getResourceDeploymentArtifactExternalAPI(resourceUUID, artifactUUID, ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER), ComponentTypeEnum.RESOURCE.toString()); + file = new File(deploymentArtifact.getFilepath() + "CP.yml"); + readFileToString = FileUtils.readFileToString(file); + Assert.assertEquals(restResponse.getResponse(), readFileToString); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifact.getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + + assertTrue("No artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(0)); + } + + } + + @DataProvider(name = "mibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption") + public static Object[][] dataProviderMibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption() { + return new Object[][]{ +// {"mibs1vFW_VFC.yml", ResourceTypeEnum.VFC}, + // TODO: delete comment below when we will have support for VL on canvas +// {"mibs1VL.yml", ResourceTypeEnum.VL}, + {"mibs1CP.yml", ResourceTypeEnum.CP} + }; + } + + // US820414 + // Import VFC/VL/CP, upload MIBs artifacts then drag it on VF & verify that deployment artifact have only download option + @Test(dataProvider = "mibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption") + public void mibsArtifacsOnResourceInstanceShouldOnlyHaveDownloadOption(String fileName, ResourceTypeEnum resourceTypeEnum) throws Exception { + +// if(resourceTypeEnum.equals(ResourceTypeEnum.CP)){ +// throw new SkipException("Open bug 322930"); +// } + + setLog(fileName); + + String filePath = FileHandling.getFilePath(folder); + + // import Resource + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(resourceTypeEnum, getUser()); + ResourceUIUtils.importVfc(resourceMetaData, filePath, fileName, getUser()); + + // 2. Upload MIBs artifacts - SNMP_TRAP & SNMP_POLL. + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<ArtifactInfo>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "SNMP_TRAP")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "SNMP_POLL")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true)); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + // 3. Check-in DataProvider resource. + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + // 4. Create VF. + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + // 5. Click on composition. + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + // 6. Drag created DataProvider resource to canvas. + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(resourceMetaData.getName()); + CanvasElement resourceInstance = vfCanvasManager.createElementOnCanvas(resourceMetaData.getName()); + + // 7. Click on DataProvider resource. + vfCanvasManager.clickOnCanvaElement(resourceInstance); + + // 8. Click on deployment artifacts in right menu. + CompositionPage.showDeploymentArtifactTab(); + + // 9. Verify that each uploaded MIBs artifacts shows in deployment artifacts. + // 10. Verify that only have download option. + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + // Hover over webelement -> check that only dowload button displayed + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + deploymentArtifact.getArtifactLabel()).isDisplayed(), true); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + deploymentArtifact.getArtifactLabel()), false); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), false); + } + + + } + + // US820414 + // Create VF, upload MIBs artifacts then drag it on service & verify that deployment artifact have only download option + @Test + public void mibsArtifacsOnVFInstanceShouldOnlyHaveDownloadOption() throws Exception { + String filePath = FileHandling.getFilePath(folder); + + // 1. Create VF. + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(resourceMetaData, getUser()); + + // 2. Upload MIBs artifacts - SNMP_TRAP & SNMP_POLL. + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<ArtifactInfo>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "SNMP_TRAP")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "SNMP_POLL")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true)); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + // 3. Check-in VF. + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + // 4. Create service. + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + // 5. Click on composition. + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + // 6. Drag created DataProvider s to canvas. + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(resourceMetaData.getName()); + CanvasElement resourceInstance = canvasManager.createElementOnCanvas(resourceMetaData.getName()); + + // 7. Click on DataProvider resource. + canvasManager.clickOnCanvaElement(resourceInstance); + + // 8. Click on deployment artifacts in right menu. + CompositionPage.showDeploymentArtifactTab(); + + // 9. Verify that each uploaded MIBs artifacts shows in deployment artifacts. + // 10. Verify that only have download option. + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + // Hover over webelement -> check that only dowload button displayed + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + deploymentArtifact.getArtifactLabel()).isDisplayed(), true); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + deploymentArtifact.getArtifactLabel()), false); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + deploymentArtifact.getArtifactLabel()); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), false); + } + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/NewArtifactTypeGuide.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/NewArtifactTypeGuide.java new file mode 100644 index 0000000000..61ac2347b2 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/NewArtifactTypeGuide.java @@ -0,0 +1,121 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.UploadArtifactPopup; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.testng.Assert; +import org.testng.annotations.Test; + +import static org.testng.AssertJUnit.assertTrue; + + +public class NewArtifactTypeGuide extends SetupCDTest { + + private String folder = ""; + + // US820276 + // Upload information artifact of type GUIDE to VF + @Test + public void crudGuideInformationArtifactForVf() throws Exception { + String filePath = FileHandling.getFilePath(folder); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(resourceMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "GUIDE"); + + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationArtifact); + + assertTrue("Only created artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + + String artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "1", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickEditArtifact(informationArtifact.getArtifactLabel()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + artifactPopup.loadFile(filePath, "CP.yml"); + artifactPopup.clickDoneButton(); + + assertTrue("Only updated artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + Assert.assertNotEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(), artifactUUID); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "2", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickDeleteArtifact(informationArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + } + + // US820276 + // Upload information artifact of type GUIDE to VFC + @Test + public void crudGuideInformationArtifactForVfc() throws Exception { + String filePath = FileHandling.getFilePath(folder); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VFC, getUser()); + ResourceUIUtils.importVfc(resourceMetaData, filePath, "guidevFW_VFC.yml", getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "GUIDE"); + + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationArtifact); + + assertTrue("Only created artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + String artifactUUID = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "1", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickEditArtifact(informationArtifact.getArtifactLabel()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + artifactPopup.loadFile(filePath, "CP.yml"); + artifactPopup.clickDoneButton(); + + assertTrue("Only updated artifact need to be exist", DeploymentArtifactPage.checkElementsCountInTable(1)); + Assert.assertNotEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + informationArtifact.getArtifactLabel()).getText(), artifactUUID); + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(informationArtifact.getArtifactLabel(), null, "2", informationArtifact.getArtifactType(), true, true, true, false); + + InformationalArtifactPage.clickDeleteArtifact(informationArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/RemoveRestrictionOfDeploymentArtifacts.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/RemoveRestrictionOfDeploymentArtifacts.java new file mode 100644 index 0000000000..877c6d50c0 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/RemoveRestrictionOfDeploymentArtifacts.java @@ -0,0 +1,116 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.UploadArtifactPopup; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + + +public class RemoveRestrictionOfDeploymentArtifacts extends SetupCDTest { + + private String folder = ""; + + // US833330 - Story [BE] - remove restriction of deployment artifacts + // Create service without resource instance and without deployment artifacts and verify it can submit for testing + @Test + public void createServiceWithoutRIAndArtifacts() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + } + + + // US833330 - Story [BE] - remove restriction of deployment artifacts + // Create service with VL resource instance and without deployment artifacts and verify it can submit for testing + @Test + public void createServiceWithVlAndWithoutArtfiacts() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.NETWORK); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.NETWORK); + canvasManager.createElementOnCanvas(LeftPanelCanvasItems.NETWORK); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + } + + // US833330 - Story [BE] - remove restriction of deployment artifacts + // Create service with VF with informational artifacts and verify it can submit for testing + @Test + public void createServiceWithInformationalArtifacts() throws Exception { + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(resourceMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + String filePath = FileHandling.getFilePath(folder); + List<ArtifactInfo> informationalArtifactList = new ArrayList<ArtifactInfo>(); + informationalArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + informationalArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "GUIDE")); + for (ArtifactInfo informationalArtifact : informationalArtifactList) { + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact, new UploadArtifactPopup(true)); + } + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(resourceMetaData.getName()); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + TesterOperationPage.certifyComponent(resourceMetaData.getName()); + reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement resourceInstance = canvasManager.createElementOnCanvas(resourceMetaData.getName()); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/Testing.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/Testing.java new file mode 100644 index 0000000000..d6c4a9f81c --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/Testing.java @@ -0,0 +1,141 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils; +import org.testng.Assert; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + + +public class Testing { + private static void validateNodeTemplatesProperties(Map<String, Map<String, Object>> predefinedMap, ToscaDefinition toscaDefinition) { + + for (String key : predefinedMap.keySet()) { + Map<String, Object> nodeTemplateProperties = getNodeTemplatePropertiesByNodeTemplateType(key, toscaDefinition); + + predefinedMap.get(key).forEach((i, j) -> { + Assert.assertEquals(nodeTemplateProperties.get(i), j, "Expected that the properties will be equal"); + }); + } + + } + + // Get properties by type + private static Map<String, Object> getNodeTemplatePropertiesByNodeTemplateType(String nodeTemplateType, ToscaDefinition toscaDefinition) { + Map<String, Object> propertiesMap = null; + + Set<String> nodeTemplates = getNodeTemplates(toscaDefinition); + + for (String nodeTemplate : nodeTemplates) { + String currentNodeTemplateType = getNodeTemplateType(toscaDefinition, nodeTemplate); + currentNodeTemplateType = currentNodeTemplateType.substring(currentNodeTemplateType.lastIndexOf(".") + 1); + if (currentNodeTemplateType.equals(nodeTemplateType)) { + propertiesMap = getNodeTemplateProperties(toscaDefinition, nodeTemplate); + break; + } + } + + return propertiesMap; + } + + // Get node templates + private static Set<String> getNodeTemplates(ToscaDefinition toscaDefinition) { + Set<String> resourceInstanceArray = toscaDefinition.getTopology_template().getNode_templates().keySet(); + return resourceInstanceArray; + } + + // Get type of node template + private static String getNodeTemplateType(ToscaDefinition toscaDefinition, String nodeTemplate) { + return toscaDefinition.getTopology_template().getNode_templates().get(nodeTemplate).getType(); + } + + // Get properties of node template + private static Map<String, Object> getNodeTemplateProperties(ToscaDefinition toscaDefinition, String nodeTemplate) { + Map<String, Object> propertiesMap = toscaDefinition.getTopology_template().getNode_templates().get(nodeTemplate).getProperties(); + return propertiesMap; + } + + + public static void main(String[] args) throws Exception { + ToscaDefinition toscaMainAmdocsDefinition, toscaMainVfDefinition, toscaMainServiceDefinition; + File filesFolder = new File("C:/Users/al714h/Downloads/Design/"); + File importToscaFilesFolder = new File("C:/Git_work/sdc/catalog-be/src/main/resources/import/tosca/"); + + File dataTypesLocation = new File(importToscaFilesFolder.getPath() + "/data-types/dataTypes.yml"); + + File genericVfFileLocation = new File(importToscaFilesFolder.getPath() + "/heat-types/Generic_VF/Generic_VF.yml"); + File genericVfcFileLocation = new File(importToscaFilesFolder.getPath() + "/heat-types/Generic_VFC/Generic_VFC.yml"); + File genericPnfFileLocation = new File(importToscaFilesFolder.getPath() + "/heat-types/Generic_PNF/Generic_PNF.yml"); + File genericServiceFileLocation = new File(importToscaFilesFolder.getPath() + "/heat-types/Generic_Service/Generic_Service.yml"); + + File amdocsCsarFileName = new File("/77e6b842669f441db20a83489da3f4be.csar"); + File VfCsarFileName = new File("/resource-Civfonboarded2016012VmxAv301072E2e1424cb9d-csar.csar"); + File serviceCsarFileName = new File("/service-Ciservicefeba0521131d-csar.csar"); + + Map<String, DataTypeDefinition> parseDataTypesYaml = FileHandling.parseDataTypesYaml(dataTypesLocation.getAbsoluteFile().toString()); + System.out.println("start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())); + + toscaMainAmdocsDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + amdocsCsarFileName)); + toscaMainVfDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + VfCsarFileName)); + toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + serviceCsarFileName)); + ToscaTopologyTemplateDefinition topologyTemplate = toscaMainAmdocsDefinition.getTopology_template(); + ToscaDefinition objectHelper = ToscaParserUtils.parseToscaYamlToJavaObject(genericVfFileLocation); + + Map<String, Object> additionalInputs = new HashMap<>(); + Set<String> keySet = objectHelper.getNode_types().keySet(); + if (keySet != null) { + for (String key : keySet) { + additionalInputs = objectHelper.getNode_types().get(key).getProperties(); + } + } +// topologyTemplate.addInputs(additionalInputs); + + +// toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(path); + System.out.println("listTypeHeatMetaDefinition start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())); +// List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(csarPath); + System.out.println("get service start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())); +// System.out.println(listTypeHeatMetaDefinition); +// for(TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition){ +// for(GroupHeatMetaDefinition groupHeatMetaDefinition : typeHeatMetaDefinition.getGroupHeatMetaDefinition()){ +// List<HeatMetaFirstLevelDefinition> artifactList = groupHeatMetaDefinition.getArtifactList(); +// boolean isBase = groupHeatMetaDefinition.getPropertyHeatMetaDefinition().getValue(); +// } +// +// } + System.out.println("Finished"); + System.out.println("get service start " + new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date())); + + + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/VfModule.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/VfModule.java new file mode 100644 index 0000000000..c1d5e6a9ba --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/US/VfModule.java @@ -0,0 +1,165 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.US; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.backend.ci.tests.utils.general.FileHandling; +import org.openecomp.sdc.be.model.Service; +import org.onap.sdc.backend.ci.tests.data.providers.OnboardingDataProviders; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.ToscaArtifactsScreenEnum; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.backend.ci.tests.execute.devCI.ArtifactFromCsar; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.DownloadManager; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.CsarParserUtils; +import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfModuleVerificator; +import org.testng.annotations.Test; + +import java.awt.*; +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import static org.testng.AssertJUnit.assertNotNull; + +/** + * @author al714h + */ + +public class VfModule extends SetupCDTest { + + + @Test + public void checkVfModulesCountAndStructure() throws Exception, AWTException { + +// String filePath = "src\\main\\resources\\Files\\VNFs"; + String filepath = org.onap.sdc.frontend.ci.tests.utilities.FileHandling.getVnfRepositoryPath(); +// String vnfFile = "LDSA.zip"; +// String vnfFile = "FDNT.zip"; + List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List<String> newRandomFileNamesFromFolder = OnboardingDataProviders.getRandomElements(1, fileNamesFromFolder); + String filePath = FileHandling.getVnfRepositoryPath(); + String vnfFile = newRandomFileNamesFromFolder.get(0); + getExtendTest().log(Status.INFO, String.format("Going to onboard the VNF %s......", vnfFile)); + System.out.println(String.format("Going to onboard the VNF %s......", vnfFile)); + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, getUser(), + vendorLicenseModel); + String vspName = createVendorSoftwareProduct.getName(); + // + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.getVspId()); + File latestFilefromDir = org.onap.sdc.frontend.ci.tests.utilities.FileHandling.getLastModifiedFileNameFromDir(); + List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(latestFilefromDir); + // + getExtendTest().log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); + HomePage.showVspRepository(); + getExtendTest().log(Status.INFO, String.format("Going to import %s......", vnfFile.substring(0, vnfFile.indexOf(".")))); + + OnboardingUiUtils.importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + // Verify deployment artifacts + Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); + LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment")); + for (HeatMetaFirstLevelDefinition deploymentArtifact : deploymentArtifacts) { + if (deploymentArtifact.getType().equals("HEAT_ENV")) { + continue; + } + System.out.println("--------------"); + System.out.println(deploymentArtifact.getFileName()); + System.out.println(deploymentArtifact.getType()); +// System.out.println(deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf("."))); + if (deploymentArtifact.getFileName().contains(".")) { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().lastIndexOf(".")), "1", deploymentArtifact.getType()); + } else { + ArtifactUIUtils.validateArtifactNameVersionType(deploymentArtifact.getFileName().trim(), "1", deploymentArtifact.getType()); + } + + } + + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); +//TODO Andrey should click on certify button + DeploymentArtifactPage.clickCertifyButton(vspName); + + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CompositionPage.searchForElement(vspName); + CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName); + assertNotNull(vfElement); + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + GeneralUIUtils.clickOnElementByTestId(ToscaArtifactsScreenEnum.TOSCA_TEMPLATE.getValue()); + latestFilefromDir = org.onap.sdc.frontend.ci.tests.utilities.FileHandling.getLastModifiedFileNameFromDir(); + +// verification + Service service = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, serviceMetadata.getName(), serviceMetadata.getVersion()); + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaYamlToJavaObject(latestFilefromDir); + +// compare number of vf modules defined in HEAT.meta file vs Service TOSCA yaml + VfModuleVerificator.compareNumberOfVfModules(listTypeHeatMetaDefinition, toscaDefinition); + VfModuleVerificator.verifyGroupMetadata(toscaDefinition, service); + + getExtendTest().log(Status.INFO, String.format("Onboarding %s test is passed ! ", vnfFile)); + + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/businesslogic/ArtifactBusinessLogic.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/businesslogic/ArtifactBusinessLogic.java new file mode 100644 index 0000000000..5794ede738 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/businesslogic/ArtifactBusinessLogic.java @@ -0,0 +1,220 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.businesslogic; + +import com.clearspring.analytics.util.Pair; +import com.google.gson.Gson; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.execute.devCI.ArtifactFromCsar; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.onap.sdc.frontend.ci.tests.datatypes.HeatAndHeatEnvNamesPair; +import org.onap.sdc.frontend.ci.tests.datatypes.HeatWithParametersDefinition; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.junit.Assert.assertTrue; + +public class ArtifactBusinessLogic { + + private static final String[] OK_FILE_EXTENSIONS = new String[]{"yaml", "yml", "env"}; + private static final String PARAMETERS = "parameters"; + private static final String DEPLOYMENT = "Deployment"; + + public static synchronized Map<String, File> createEnvFilesListFromCsar(String vspName, String filePath) throws Exception { + Map<String, File> generatedEnvFiles; + File csarFile = HomePage.downloadVspCsarToDefaultDirectory(vspName); + FileHandling.unzip(csarFile.toString(), filePath); + List<File> yamlList = getHeatFilesCreatedFromCsar(csarFile, filePath); + Map<String, HeatAndHeatEnvNamesPair> filesPairMap = getFilesPairMap(yamlList); + generatedEnvFiles = generateDefaultEnvFiles(filesPairMap, filePath); + return generatedEnvFiles; + } + + public static synchronized List<File> getHeatFilesCreatedFromCsar(File pathToDirectory, String filePath) throws Exception { + List<File> fileList = new ArrayList<>(); + String artifactsFilePath = filePath + "Artifacts" + File.separator; + List<File> fileListFromArtifactsDirectory = FileHandling.getHeatAndHeatEnvArtifactsFromZip(new File(artifactsFilePath), OK_FILE_EXTENSIONS); + Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(pathToDirectory.toString()); + LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = (LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get(DEPLOYMENT); + for (HeatMetaFirstLevelDefinition deploymentArtifact : deploymentArtifacts) { + String type = deploymentArtifact.getType(); + if (type.equals(ArtifactTypeEnum.HEAT.getType()) + || type.equals(ArtifactTypeEnum.HEAT_ENV.getType()) + || type.equals(ArtifactTypeEnum.HEAT_VOL.getType()) + || type.equals(ArtifactTypeEnum.HEAT_NET.getType())) { + File file = new File(artifactsFilePath + deploymentArtifact.getFileName()); + if (fileListFromArtifactsDirectory.contains(file)) { + fileList.add(file); + } else { + assertTrue("File " + file + " does not exist", false); + } + } + } + return fileList; + } + + private static synchronized Map<String, HeatAndHeatEnvNamesPair> getFilesPairMap(List<File> generatedEnvFiles) { + + Map<String, HeatAndHeatEnvNamesPair> heatAndHeatEnvPairs = new HashMap<>(); + for (File file : generatedEnvFiles) { + String[] fileName = file.getName().split("\\."); + String currentKey = fileName[0]; + String currentExtension = fileName[1]; + HeatAndHeatEnvNamesPair pair; + if (!heatAndHeatEnvPairs.containsKey(currentKey)) { + pair = new HeatAndHeatEnvNamesPair(); + heatAndHeatEnvPairs.put(currentKey, pair); + } else { + pair = heatAndHeatEnvPairs.get(currentKey); + } + setFileToPair(file, currentExtension, pair); + } + return heatAndHeatEnvPairs; + } + + /** + * The method fill list of HeatWithParametersDefinition parameters + * + * @param deploymentArtifacts + * @return + */ + public static synchronized List<HeatWithParametersDefinition> extractHeatWithParametersDefinition(Map<String, ArtifactDefinition> deploymentArtifacts) { + + List<HeatWithParametersDefinition> heatAndEnvLabelList = new ArrayList<>(); + + for (Entry<String, ArtifactDefinition> artifactDefinitionChild : deploymentArtifacts.entrySet()) { + if (artifactDefinitionChild.getValue().getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) { + for (Entry<String, ArtifactDefinition> artifactDefinitionParent : deploymentArtifacts.entrySet()) { + if (artifactDefinitionChild.getValue().getGeneratedFromId().equals(artifactDefinitionParent.getValue().getUniqueId())) { + String heatLabel = artifactDefinitionParent.getValue().getArtifactLabel(); + String heatArtifactType = artifactDefinitionParent.getValue().getArtifactType(); + String heatArtifactDisplayName = artifactDefinitionParent.getValue().getArtifactDisplayName(); + List<HeatParameterDataDefinition> heatParameterDefinition = artifactDefinitionParent.getValue().getHeatParameters(); + String heatEnvLabel = artifactDefinitionChild.getValue().getArtifactLabel(); + String heatEnvArtifactType = artifactDefinitionChild.getValue().getArtifactType(); + heatAndEnvLabelList.add(new HeatWithParametersDefinition(heatLabel, heatEnvLabel, heatArtifactType, heatEnvArtifactType, heatArtifactDisplayName, heatParameterDefinition)); + break; + } + } + } + } + return heatAndEnvLabelList; + } + + + private static synchronized void setFileToPair(File file, String currentExtension, HeatAndHeatEnvNamesPair pair) { + if (!currentExtension.equals("env")) { + pair.setHeatFileName(file); + } else { + pair.setHeatEnvFileName(file); + } + } + + private static synchronized Map<String, File> generateDefaultEnvFiles(Map<String, HeatAndHeatEnvNamesPair> filesPairMap, String filePath) throws Exception { + + Map<String, File> generatedEnvFilesMap = new HashMap<>(); + for (Entry<String, HeatAndHeatEnvNamesPair> pair : filesPairMap.entrySet()) { + Map<String, Pair<String, Object>> envParametersMap = getEnvParametersMap(pair); + File generatedEnvFile = createEnvFile(envParametersMap, new File(filePath + pair.getKey() + ".env")); + generatedEnvFilesMap.put(pair.getKey(), generatedEnvFile); + } + return generatedEnvFilesMap; + } + + private static synchronized File createEnvFile(Map<String, Pair<String, Object>> envParametersMap, File fileToWrite) throws IOException { + + FileHandling.writeToFile(fileToWrite, PARAMETERS + ":", 0); + FileHandling.writeToFile(fileToWrite, envParametersMap, 2); + return fileToWrite; + } + + private static synchronized Map<String, Pair<String, Object>> getEnvParametersMap(Entry<String, HeatAndHeatEnvNamesPair> pair) throws Exception { + File heatFileName = pair.getValue().getHeatFileName(); + File heatEnvFileName = pair.getValue().getHeatEnvFileName(); + Map<String, Pair<String, Object>> envParametersMap = new HashMap<>(); + fillParametersMapFromHeatFile(heatFileName, envParametersMap); + fillParametersMapFromHeatEnvFile(heatEnvFileName, envParametersMap); + return envParametersMap; + } + + private static synchronized void fillParametersMapFromHeatEnvFile(File heatEnvFileName, Map<String, Pair<String, Object>> envParametersMap) throws Exception { + if (heatEnvFileName != null) { + Map<String, Object> mapHeatEnvFileParameters = FileHandling.parseYamlFileToMapByPattern(heatEnvFileName, PARAMETERS); + for (Map.Entry<String, Object> parameter : mapHeatEnvFileParameters.entrySet()) { + String key = parameter.getKey(); + Pair<String, Object> pair; + if (envParametersMap.containsKey(key)) { + if (envParametersMap.get(key).left.equals("string") && parameter.getValue() != null) { + pair = Pair.create(envParametersMap.get(key).left, "\"" + parameter.getValue() + "\""); + } else if (envParametersMap.get(key).left.equals("string") && parameter.getValue() == null) { + pair = Pair.create(envParametersMap.get(key).left, ""); + } else if (parameter.getValue() == null) { + pair = Pair.create(envParametersMap.get(key).left, ""); + } else if (envParametersMap.get(key).left.equals("json") && parameter.getValue() != null) { + String pairValue = ""; + Gson gson = new Gson(); + if (parameter.getValue() instanceof java.util.LinkedHashMap) { + pairValue = gson.toJson(parameter.getValue()); + } + pair = Pair.create(envParametersMap.get(key).left, pairValue); + + } else if (envParametersMap.get(key).left.equals("json") && parameter.getValue() == null) { + pair = Pair.create(envParametersMap.get(key).left, ""); + } else { + pair = Pair.create(envParametersMap.get(key).left, parameter.getValue()); + } + envParametersMap.put(key, pair); + } + } + } + } + + @SuppressWarnings("unchecked") + private static synchronized void fillParametersMapFromHeatFile(File heatFileName, Map<String, Pair<String, Object>> envParametersMap) throws Exception { + Map<String, Object> mapHeatFileParameters = FileHandling.parseYamlFileToMapByPattern(heatFileName, PARAMETERS); + for (Map.Entry<String, Object> parameter : mapHeatFileParameters.entrySet()) { + Map<String, Object> value = (Map<String, Object>) parameter.getValue(); + Pair<String, Object> pair; + if (value.get("type").toString().equals("string") && value.get("default") != null) { + pair = Pair.create(value.get("type").toString(), "\"" + value.get("default") + "\""); + } else if (value.get("type").toString().equals("string") && value.get("default") == null) { + pair = Pair.create(value.get("type").toString(), ""); + } else if (value.get("default") == null) { + pair = Pair.create(value.get("type").toString(), ""); + } else { + pair = Pair.create(value.get("type").toString(), value.get("default")); + } + envParametersMap.put(parameter.getKey(), pair); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/dataProvider/OnbordingDataProviders.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/dataProvider/OnbordingDataProviders.java new file mode 100644 index 0000000000..0dee90f5cf --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/dataProvider/OnbordingDataProviders.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.dataProvider; + +import org.onap.sdc.backend.ci.tests.datatypes.enums.XnfTypeEnum; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.testng.Assert; +import org.testng.annotations.DataProvider; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class OnbordingDataProviders { + + private static final String VSP_VGW_CSAR = "vsp-vgw.csar"; + private static final int NUMBER_OF_RANDOMLY_ONBOARD_VNF = 3; + protected static String filepath = FileHandling.getVnfRepositoryPath(); + + // -----------------------dataProviders----------------------------------------- + @DataProvider(name = "randomVNF_List", parallel = false) + private static Object[][] randomVnfList() throws Exception { + int randomElementNumber = NUMBER_OF_RANDOMLY_ONBOARD_VNF; //how many VNFs to onboard randomly + List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List<String> 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 Object[][] VnfList() throws Exception { + + List<String> fileNamesFromFolder = OnboardingUtils.getXnfNamesFileList(XnfTypeEnum.VNF); + + System.out.println(String.format("There are %s zip file(s) to test", fileNamesFromFolder.size())); + return provideData(fileNamesFromFolder, filepath); + } + + @DataProvider(name = "updateList") + private static Object[][] updateList() throws Exception { + + Object[][] objectArr = new Object[2][]; + + Object[][] filteredArObject = null; + + objectArr[0] = new Object[] {"1-2016-20-visbc3vf-(VOIP)_v2.1.zip", + "2-2016-20-visbc3vf-(VOIP)_v2.1_RenameResourceToShay.zip"}; + objectArr[1] = new Object[] {"1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip", + "2-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0_Added2TestParameters.zip"}; + + filteredArObject = OnboardingUtils.filterObjectArrWithExcludedVnfs(objectArr); + + return filteredArObject; + + + } + + @DataProvider(name = "Single_Vsp_Test_Csar", parallel = true) + private static Object[][] singleVspTestCsar() throws Exception { + + List<String> fileNamesFromFolder = OnboardingUtils.getXnfNamesFileList(XnfTypeEnum.VNF); + if (!fileNamesFromFolder.contains(VSP_VGW_CSAR)) { + Assert.fail("Vsp Test file is not exits in the path"); + } + return provideData(Arrays.asList(VSP_VGW_CSAR), filepath); + } + + // -----------------------methods----------------------------------------- + static Object[][] provideData(List<String> fileNamesFromFolder, String filepath) { + + Object[][] arObject = new Object[fileNamesFromFolder.size()][]; + int index = 0; + for (Object obj : fileNamesFromFolder) { + arObject[index++] = new Object[] {filepath, obj}; + } + return arObject; + } + + static List<String> getRandomElements(int randomElementNumber, List<String> fileNamesFromFolder) { + if (fileNamesFromFolder.size() == 0 || fileNamesFromFolder.size() < randomElementNumber) { + return null; + } else { + List<Integer> indexList = new ArrayList<>(); + List<String> 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 (Integer integer : randomArray) { + newRandomFileNamesFromFolder.add(fileNamesFromFolder.get(integer)); + } + return newRandomFileNamesFromFolder; + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ArtifactInfo.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ArtifactInfo.java new file mode 100644 index 0000000000..80e471300b --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ArtifactInfo.java @@ -0,0 +1,105 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public class ArtifactInfo { + + private String filepath; + private String filename; + private String description; + private String artifactType; + private String artifactLabel; + private String artifactVersion; + + public ArtifactInfo(String filepath, String filename, String description, String artifactLabel, + String artifactType) { + super(); + this.filepath = filepath; + this.filename = filename; + this.description = description; + this.artifactType = artifactType; + this.artifactLabel = artifactLabel; + } + + public ArtifactInfo(String filepath, String filename, String description, String artifactLabel, + String artifactType, String artifactVersion) { + super(); + this.filepath = filepath; + this.filename = filename; + this.description = description; + this.artifactType = artifactType; + this.artifactLabel = artifactLabel; + this.artifactVersion = artifactVersion; + } + + public ArtifactInfo() { + super(); + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getFilepath() { + return filepath; + } + + public void setFilepath(String filepath) { + this.filepath = filepath; + } + + public String getFilename() { + return filename; + } + + public void setFilename(String filename) { + this.filename = filename; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getArtifactType() { + return artifactType; + } + + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public String getArtifactLabel() { + return artifactLabel; + } + + public void setArtifactLabel(String artifactLabel) { + this.artifactLabel = artifactLabel; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CanvasElement.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CanvasElement.java new file mode 100644 index 0000000000..8c034482c7 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CanvasElement.java @@ -0,0 +1,98 @@ +/*-
+ * ============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.onap.sdc.frontend.ci.tests.datatypes;
+
+import org.apache.commons.lang3.tuple.ImmutablePair;
+
+public final class CanvasElement {
+ private final String uniqueId;
+ private ImmutablePair<Integer, Integer> location;
+ private DataTestIdEnum.LeftPanelCanvasItems normativeElementType;
+ private String elementType;
+ private String elementNameOnCanvas;
+
+ CanvasElement(String name, ImmutablePair<Integer, Integer> location, DataTestIdEnum.LeftPanelCanvasItems canvasItem) {
+ super();
+ this.uniqueId = name;
+ this.location = location;
+ normativeElementType = canvasItem;
+ this.elementNameOnCanvas = generateCanvasName(name);
+ }
+
+ CanvasElement(String name, ImmutablePair<Integer, Integer> location, String canvasItem) {
+ super();
+ this.uniqueId = name;
+ this.location = location;
+ elementType = canvasItem;
+ this.elementNameOnCanvas = generateCanvasNameFromCanvasItem(canvasItem);
+ }
+
+ public CanvasElement(String name, ImmutablePair<Integer, Integer> location) {
+ super();
+ this.uniqueId = name;
+ this.location = location;
+ this.elementNameOnCanvas = generateCanvasName(name);
+ }
+
+ public String generateCanvasName(String name) {
+ if (name.toLowerCase().contains("service")) {
+ return name.toLowerCase().substring(0, name.indexOf("_")) + "_proxy 0";
+ }
+ return name.substring(0, name.indexOf("_")) + " 0";
+ }
+
+ public String generateCanvasNameFromCanvasItem(String name) {
+ if (name.toLowerCase().contains("service")) {
+ return name.toLowerCase() + "_proxy 0";
+ }
+ return name + " 0";
+ }
+
+ public String getUniqueId() {
+ return uniqueId;
+ }
+
+ public ImmutablePair<Integer, Integer> getLocation() {
+ return location;
+ }
+
+ public void setLocation(ImmutablePair<Integer, Integer> location) {
+ this.location = location;
+ }
+
+ public DataTestIdEnum.LeftPanelCanvasItems getNormativeElementType() {
+ return normativeElementType;
+ }
+
+ public String getElementType() {
+ return elementType;
+ }
+
+ public String getElementNameOnCanvas() {
+ return elementNameOnCanvas;
+ }
+
+ public void setElementNameOnCanvas(String newName) {
+ elementNameOnCanvas = newName;
+ }
+
+
+}
diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CanvasManager.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CanvasManager.java new file mode 100644 index 0000000000..560f342ea5 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CanvasManager.java @@ -0,0 +1,622 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.sdc.backend.ci.tests.datatypes.enums.CircleSize; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesAssignmentPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertyNameBuilder; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.By; +import org.openqa.selenium.StaleElementReferenceException; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.testng.Assert; +import org.testng.SkipException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +public final class CanvasManager { + public static final int VIEW_BUTTON_X_DELTA = 30; + public static final int VIEW_BUTTON_Y_DELTA = 11; + public static final int DELTET_BUTTON_X_DELTA = 30; + public static final int CANVAS_ELEMENT_TYPE_SPLITER = 4; + public static final int MAX_WAIT_DIVIDER = 1000; + public static final int THREAD_SLEEP_TIME = 5000; + private Map<String, CanvasElement> canvasElements; + private Actions actions; + private WebElement canvas; + private int reduceCanvasWidthFactor; + private CanvasElement canvasElement; + // Offsets Are used to find upper right corner of canvas element in order to + // connect links + private static final int CANVAS_VF_Y_OFFSET = 30; + private static final int CANVAS_VF_X_OFFSET = 18; // 14 - 27 + + private static final int CANVAS_NORMATIVE_ELEMENT_Y_OFFSET = 12; + private static final int CANVAS_NORMATIVE_ELEMENT_X_OFFSET = 7; + + private static final int CANVAS_SERVICE_Y_OFFSET = 27; + private static final int CANVAS_SERVICE_X_OFFSET = 16; + + private CanvasManager() { + canvasElements = new HashMap<>(); + actions = new Actions(GeneralUIUtils.getDriver()); + canvas = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS.getValue()); + try { + WebElement webElement = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.CANVAS_RIGHT_PANEL.getValue()); + reduceCanvasWidthFactor = webElement.getSize().width; + } catch (Exception e) { + reduceCanvasWidthFactor = 0; + } + } + + public static CanvasManager getCanvasManager() { + return new CanvasManager(); + } + + public List<CanvasElement> getCanvasElements() { + return canvasElements.values().stream().collect(Collectors.toList()); + } + + private void addCanvasElement(CanvasElement element) { + String prefix = element.getElementType(); + List<CanvasElement> canvasElementsFromSameTemplate = new ArrayList<>(); + + // collect all elements from from same template + for (CanvasElement currElement : canvasElements.values()) { + if (currElement.getElementNameOnCanvas().toLowerCase().startsWith(prefix.toLowerCase())) { + canvasElementsFromSameTemplate.add(currElement); + } + } + + // match element name to actual name on canvas + if (canvasElementsFromSameTemplate.size() > 0) { + String newName = prefix + " " + canvasElementsFromSameTemplate.size(); + element.setElementNameOnCanvas(newName); + } + + canvasElements.put(element.getUniqueId(), element); + } + + private void moveElementOnCanvas(CanvasElement canvasElement, ImmutablePair<Integer, Integer> newLocation) + throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.clickAndHold(); + actions.moveToElement(canvas, newLocation.left, newLocation.right); + actions.release(); + actions.perform(); + canvasElement.setLocation(newLocation); + GeneralUIUtils.waitForLoader(); + + } + + public void moveToFreeLocation(String containerName) { + final int maxWait = 5000; + final int napPeriod = 200; + int sumOfWaiting = 0; + boolean isKeepWaiting = false; + while (!isKeepWaiting) { + ImmutablePair<Integer, Integer> freePosition = getFreePosition(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.clickAndHold(); + actions.release(); + actions.perform(); + isKeepWaiting = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText() + .equals(containerName); + sumOfWaiting += napPeriod; + if (sumOfWaiting > maxWait) { + Assert.fail("Can't click on VF"); + } + } + } + + public void clickOnCanvaElement(CanvasElement canvasElement) { + ImmutablePair<Integer, Integer> coordinates = getElementCoordinates(canvasElement.getElementNameOnCanvas()); + actions.moveToElement(canvas, coordinates.left, coordinates.right); + actions.clickAndHold(); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + actions.click().perform(); + GeneralUIUtils.ultimateWait(); + + validateInstanceSelected(canvasElement); + ExtentTestActions.log(Status.INFO, String.format("Canvas element %s selected", canvasElement.getElementType())); + } + + public void openLinkPopupReqsCapsConnection(CanvasElement canvasElement) { + ExtentTestActions.log(Status.INFO, "Open Link popup"); + clickOnCanvasLink(canvasElement); + int x = canvasElement.getLocation().getLeft() + VIEW_BUTTON_X_DELTA; + int y = canvasElement.getLocation().getRight() + VIEW_BUTTON_Y_DELTA; + clickOnCanvasPosition(x, y); + GeneralUIUtils.ultimateWait(); + } + + public void openLinkPopupReqsCapsConnection(CanvasElement sourceElement, CanvasElement destElement) { + ExtentTestActions.log(Status.INFO, "Open Link popup"); + ImmutablePair<Integer, Integer> sourceCoordinates = getElementCoordinates(sourceElement.getElementNameOnCanvas()); + ImmutablePair<Integer, Integer> destCoordinates = getElementCoordinates(destElement.getElementNameOnCanvas()); + ImmutablePair<Integer, Integer> linkPosition = calcMidOfLink(sourceCoordinates, destCoordinates); + + clickOnCanvasPosition(linkPosition.left, linkPosition.right); // click on link + int x = linkPosition.left + VIEW_BUTTON_X_DELTA; + int y = linkPosition.right + VIEW_BUTTON_Y_DELTA; + clickOnCanvasPosition(x, y); // click on view popup + GeneralUIUtils.ultimateWait(); + } + + public void closeLinkPopupReqsCapsConnection() { + GeneralUIUtils.clickOnElementByTestId("Cancel"); + //GeneralUIUtils.ultimateWait(); + } + + public void clickSaveOnLinkPopup() { + ExtentTestActions.log(Status.INFO, "Click save on link popup"); + GeneralUIUtils.clickOnElementByTestId("Save"); + //GeneralUIUtils.ultimateWait(); + } + + public void deleteLinkPopupReqsCapsConnection(CanvasElement canvasElement) { + ExtentTestActions.log(Status.INFO, "Delete Link "); + clickOnCanvasLink(canvasElement); + int x = canvasElement.getLocation().getLeft() + DELTET_BUTTON_X_DELTA; + int y = canvasElement.getLocation().getRight() + DELTET_BUTTON_X_DELTA; + clickOnCanvasPosition(x, y); + } + + public void deleteLinkPopupReqsCapsConnection(CanvasElement sourceElement, CanvasElement destElement) { + ExtentTestActions.log(Status.INFO, "Delete Link "); + ImmutablePair<Integer, Integer> sourceCoordinates = getElementCoordinates(sourceElement.getElementNameOnCanvas()); + ImmutablePair<Integer, Integer> destCoordinates = getElementCoordinates(destElement.getElementNameOnCanvas()); + ImmutablePair<Integer, Integer> linkPosition = calcMidOfLink(sourceCoordinates, destCoordinates); + clickOnCanvasPosition(linkPosition.left, linkPosition.right); // click on link + int x = linkPosition.left + DELTET_BUTTON_X_DELTA; + int y = linkPosition.right + DELTET_BUTTON_X_DELTA; + clickOnCanvasPosition(x, y); + } + + public void clickOnCanvasLink(CanvasElement canvasElement) { + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click().perform(); + GeneralUIUtils.ultimateWait(); + } + + public void clickOnCanvasPosition(int x, int y) { + + try { + actions.moveToElement(canvas, x, y); + actions.click(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + } catch (Exception e) { + System.out.println(e); + } + } + + public void moveElementOnCanvas(CanvasElement canvasElement) throws Exception { + moveElementOnCanvas(canvasElement, getFreePosition()); + } + + public void deleteElementFromCanvas(CanvasElement canvasElement) throws Exception { + GeneralUIUtils.waitForLoader(); + actions.moveToElement(canvas, canvasElement.getLocation().left, canvasElement.getLocation().right); + actions.click(); + actions.perform(); + ExtentTestActions.log(Status.INFO, String.format("Removing canvas element %s ", canvasElement.getElementType())); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.DELETE_INSTANCE_CANCEL.getValue()).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.DELETE_INSTANCE_BUTTON.getValue()) + .click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.DELETE_INSTANCE_OK.getValue()).click(); + canvasElements.remove(canvasElement.getUniqueId()); + GeneralUIUtils.ultimateWait(); + if (canvasElement.getElementType().contains("-")) { + ExtentTestActions.log(Status.INFO, String.format( + "Canvas element %s is removed", + canvasElement.getElementType().split("-")[CANVAS_ELEMENT_TYPE_SPLITER])); + } else { + ExtentTestActions.log(Status.INFO, String.format( + "Canvas element %s is removed", + canvasElement.getElementType())); + } + } + + private WebElement findClickElement(String dataTestId) { + int attempts = 0; + while (attempts < 2) { + try { + return GeneralUIUtils.getWebElementByTestID(dataTestId); + } catch (StaleElementReferenceException e) { + } + attempts++; + } + return null; + } + + public CanvasElement createElementOnCanvas(String elementName) { + String actionDuration = GeneralUIUtils.getActionDuration(() -> { + try { + canvasElement = createElementOnCanvasWithoutDuration(elementName); + } catch (Exception e) { + e.printStackTrace(); + } + }); + + if (canvasElement != null) { + ExtentTestActions.log(Status.INFO, String.format("The element %s should now be on the canvas", elementName), actionDuration); + } + return canvasElement; + } + + private CanvasElement createElementOnCanvasWithoutDuration(String elementDataTestId) throws Exception { + final int offset = 20; + try { + CompositionPage.searchForElement(elementDataTestId); + WebElement element = findClickElement(elementDataTestId); + ImmutablePair<Integer, Integer> freePosition = getFreePosition(); + actions.moveToElement(element, offset, offset); + actions.clickAndHold(); + actions.moveToElement(canvas, freePosition.left, freePosition.right); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + String uniqueId = elementDataTestId + "_" + UUID.randomUUID().toString(); + CanvasElement canvasElement = new CanvasElement(uniqueId, freePosition, elementDataTestId); + addCanvasElement(canvasElement); + GeneralUIUtils.ultimateWait(); + return canvasElement; + } catch (Exception e) { + System.out.println("Can't create element on canvas"); + e.printStackTrace(); + } + return null; + } + + public CanvasElement createElementOnCanvas(LeftPanelCanvasItems canvasItem) { + return createElementOnCanvas(canvasItem.getValue()); + } + + private ImmutablePair<Integer, Integer> getFreePosition() { + ImmutablePair<Integer, Integer> randomPosition = null; + boolean freePosition = false; + final int minSpace = 150; + while (!freePosition) { + ImmutablePair<Integer, Integer> tempRandomPosition = getRandomPosition(); + freePosition = !canvasElements.values().stream().map(e -> e.getLocation()) + .filter(e -> Math.abs(e.left - tempRandomPosition.left) < minSpace + && Math.abs(e.right - tempRandomPosition.right) < minSpace) + .findAny().isPresent(); + randomPosition = tempRandomPosition; + } + return randomPosition; + } + + private ImmutablePair<Integer, Integer> getRandomPosition() { + final int edgeBuffer = 50; + Random random = new Random(); + int xElement = random.nextInt(canvas.getSize().width - 2 * edgeBuffer - reduceCanvasWidthFactor) + edgeBuffer; + int yElement = random.nextInt(canvas.getSize().height - 2 * edgeBuffer) + edgeBuffer; + return new ImmutablePair<Integer, Integer>(xElement, yElement); + } + + // Will work only if 2 elements are big sized (VF size), if one of the elements is Small use the function linkElements + public void linkElements(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + ExtentTestActions.log(Status.INFO, String.format("Linking between the %s instance and the %s instance.", firstElement.getElementType(), secondElement.getElementType())); + drawSimpleLink(firstElement.getElementNameOnCanvas(), secondElement.getElementNameOnCanvas()); + selectReqAndCapAndConnect(); + ExtentTestActions.log(Status.INFO, String.format("The instances %s and %s should now be connected.", firstElement.getElementType(), secondElement.getElementType())); + } + + // old version, depricated + public void linkElements(CanvasElement firstElement, CircleSize firstElementSize, CanvasElement secondElement, CircleSize secondElementSize) throws Exception { + drawSimpleLink(firstElement, firstElementSize, secondElement, secondElementSize); + selectReqAndCapAndConnect(); + ExtentTestActions.log(Status.INFO, String.format("The instances %s and %s should now be connected.", firstElement.getElementType(), secondElement.getElementType())); + } + + public void linkElements(String firstElement, String secondElement) throws Exception { + drawSimpleLink(firstElement, secondElement); + selectReqAndCapAndConnect(); + ExtentTestActions.log(Status.INFO, String.format("The instances %s and %s should now be connected.", firstElement, secondElement)); + } + + // use JS to get coordinates of elements + private void drawSimpleLink(String firstElement, String secondElement) { + ImmutablePair<Integer, Integer> firstElementCoordinates = getGreenDotCoordinatesOfElement(firstElement); + ImmutablePair<Integer, Integer> secondElementCoordinates = getElementCoordinates(secondElement); + + actions.moveToElement(canvas, firstElementCoordinates.left, firstElementCoordinates.right); + actions.perform(); + actions.moveToElement(canvas, firstElementCoordinates.left, firstElementCoordinates.right); + actions.clickAndHold(); + actions.moveToElement(canvas, secondElementCoordinates.left, secondElementCoordinates.right); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + } + + private void selectReqAndCapAndConnect() throws Exception { + addFirstReqOrCapAndPressNext(); + addFirstReqOrCapAndPressNext(); + linkMenuClickOnFinishButton(); + } + + private void addFirstReqOrCapAndPressNext() throws Exception { + addFirstReqOrCap(); + linkMenuClickOnNextButton(); + } + + private void addFirstReqOrCap() { + GeneralUIUtils.getWebElementsListByClassName(DataTestIdEnum.LinkMenuItems.LINK_ITEM_CAP_OR_REQ.getValue()).get(0).click(); + } + + private void linkMenuClickOnNextButton() throws Exception { + GeneralUIUtils.clickOnElementByText("Next"); + GeneralUIUtils.ultimateWait(); + } + + private void linkMenuClickOnFinishButton() throws Exception { + GeneralUIUtils.clickOnElementByText("Finish"); + GeneralUIUtils.ultimateWait(); + } + + + private void drawSimpleLink(CanvasElement firstElement, CanvasElement secondElement) throws Exception { + int yOffset = CANVAS_VF_Y_OFFSET; + int xOffset = CANVAS_VF_X_OFFSET; + + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, secondElement.getLocation().right - yOffset); + actions.release(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + } + + private void drawSimpleLink(CanvasElement firstElement, CircleSize firstElementSize, CanvasElement secondElement, CircleSize secondElementSize) throws Exception { + ExtentTestActions.log(Status.INFO, String.format("Linking between the %s instance and the %s instance.", firstElement.getElementType(), secondElement.getElementType())); + Integer yOffset = getCircleOffset(firstElementSize).right; + Integer xOffset = getCircleOffset(firstElementSize).left; + firstElement.getElementType(); + + + actions.moveToElement(canvas, firstElement.getLocation().left + xOffset, + firstElement.getLocation().right - yOffset); + + actions.clickAndHold(); + + yOffset = getCircleOffset(secondElementSize).right; + xOffset = getCircleOffset(secondElementSize).left; + + actions.moveToElement(canvas, secondElement.getLocation().left + xOffset, secondElement.getLocation().right - yOffset); + actions.release(); + actions.build(); + actions.perform(); + GeneralUIUtils.ultimateWait(); + } + + private Pair<Integer, Integer> getCircleOffset(CircleSize circleSize) { + Pair<Integer, Integer> circleSizes; + if (circleSize.equals(CircleSize.VF)) { + circleSizes = new Pair<Integer, Integer>(CANVAS_VF_X_OFFSET, CANVAS_VF_Y_OFFSET); + } else if (circleSize.equals(CircleSize.NORMATIVE)) { + circleSizes = new Pair<Integer, Integer>(CANVAS_NORMATIVE_ELEMENT_X_OFFSET, CANVAS_NORMATIVE_ELEMENT_Y_OFFSET); + } else { + circleSizes = new Pair<Integer, Integer>(CANVAS_SERVICE_X_OFFSET, CANVAS_SERVICE_Y_OFFSET); + } + return circleSizes; + } + + public String updateElementNameInCanvas(CanvasElement canvasElement, String newInstanceName) { + GeneralUIUtils.ultimateWait(); + clickOnCanvaElement(canvasElement); + GeneralUIUtils.getWebElementBy(By.id("editPencil")).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.RENAME_INSTANCE_CANCEL.getValue()).click(); + GeneralUIUtils.getWebElementBy(By.id("editPencil")).click(); + WebElement instanceNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralCanvasItems.INSTANCE_NAME_FIELD.getValue()); + String oldInstanceName = instanceNameField.getAttribute("value"); + instanceNameField.clear(); + instanceNameField.sendKeys(newInstanceName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.RENAME_INSTANCE_OK.getValue()).click(); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("w-sdc-modal-resource-instance-name")); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Name of element instance changed from %s to %s", oldInstanceName, newInstanceName)); + return oldInstanceName; + } + + /** + * @param canvasElement Validate that instance was selected on right sidebar + */ + private void validateInstanceSelected(CanvasElement canvasElement) { + final long maxWait = 5000; + final long napPeriod = 200; + long sumOfWaiting = 0; + boolean isInstanceSelected; + do { + isInstanceSelected = CompositionPage.getSelectedInstanceName().toLowerCase().contains(canvasElement.getElementType().toLowerCase()); + + if (!isInstanceSelected) { + try { + TimeUnit.MILLISECONDS.sleep(napPeriod); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + sumOfWaiting += napPeriod; + if (sumOfWaiting > maxWait) { + throw new SkipException(String.format("Bug 342260, can't select instance properly, waited for %s seconds after click on instance", (int) (maxWait / MAX_WAIT_DIVIDER))); + } + } while (!isInstanceSelected); + } + + public void validateLinkIsSelected() { + final long maxWait = 5000; + final long napPeriod = 200; + long sumOfWaiting = 0; + boolean isInstanceSelected; + do { + isInstanceSelected = GeneralUIUtils.isWebElementExistByClass("w-sdc-menu-item w-sdc-canvas-menu-item-view"); + + if (!isInstanceSelected) { + try { + TimeUnit.MILLISECONDS.sleep(napPeriod); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + + sumOfWaiting += napPeriod; + if (sumOfWaiting > maxWait) { + Assert.fail(String.format("Can't select link properly, waited for %s seconds", (int) (maxWait / MAX_WAIT_DIVIDER))); + } + } while (!isInstanceSelected); + } + + private void selectReqCapByName(String reqCapName) { + GeneralUIUtils.clickOnElementByText(reqCapName); + GeneralUIUtils.ultimateWait(); + } + + private void selectTypeOfReqCap(String dataTestId, String reqCapType) { + GeneralUIUtils.selectByValueTextContained(dataTestId, reqCapType); + } + + public void linkElementsAndSelectCapReqTypeAndCapReqName(CanvasElement firstElement, CanvasElement secondElement, ConnectionWizardPopUpObject connectionWizardPopUpObject) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating link between %s and %s", firstElement.getElementType(), secondElement.getElementType())); + drawSimpleLink(firstElement.getElementNameOnCanvas(), secondElement.getElementNameOnCanvas()); + selectTypeOfReqCap(DataTestIdEnum.LinkMenuItems.REQ_CAP_SELECT_DATA_TESTS_ID.getValue(), connectionWizardPopUpObject.getCapabilityTypeSecondItem()); + addFirstReqOrCapAndPressNext(); + selectReqCapByName(connectionWizardPopUpObject.getCapabilityNameSecondItem()); + linkMenuClickOnNextButton(); + linkMenuClickOnFinishButton(); + } + + public Map<String, String> linkElementsWithCapPropAssignment(CanvasElement firstElement, CanvasElement secondElement, ConnectionWizardPopUpObject connectionWizardPopUpObject) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating link between %s and %s", firstElement.getElementType(), secondElement.getElementType())); + drawSimpleLink(firstElement.getElementNameOnCanvas(), secondElement.getElementNameOnCanvas()); + selectTypeOfReqCap(DataTestIdEnum.LinkMenuItems.REQ_CAP_SELECT_DATA_TESTS_ID.getValue(), connectionWizardPopUpObject.getCapabilityTypeSecondItem()); + addFirstReqOrCapAndPressNext(); + selectReqCapByName(connectionWizardPopUpObject.getCapabilityNameSecondItem()); + linkMenuClickOnNextButton(); + Map<String, String> mapOfValues = connectionWizardAssignCapPropValues(); + linkMenuClickOnFinishButton(); + Thread.sleep(THREAD_SLEEP_TIME); + return mapOfValues; + } + + + public Map<String, String> connectionWizardAssignCapPropValues() throws Exception { + //get list of capability property value fields data-tests-ids in connection wizard + List<String> valueField = getListOfValueFieldIDs(); + //get map of field ids and their values, fill in values if empty + Map<String, String> propValues = getMapOfCapPropValues(valueField, true); + return propValues; + } + + public Map<String, String> connectionWizardCollectCapPropValues() throws Exception { + //get list of capability property value fields data-tests-ids in connection wizard + List<String> valueField = getListOfValueFieldIDs(); + //get map of field ids and their values, collect existing values + Map<String, String> propValues = getMapOfCapPropValues(valueField, false); + return propValues; + } + + private List<String> getListOfValueFieldIDs() { + String propName = GeneralUIUtils.getWebElementsListByContainsClassName("multiline-ellipsis-content").get(0).getText(); + List<WebElement> valueNameElement = GeneralUIUtils.findElementsByXpath("//div[@class='dynamic-property-row nested-level-1']/div[1]"); + List<String> valueName = new ArrayList<>(); + for (int i = 0; i < valueNameElement.size(); i++) { + valueName.add(valueNameElement.get(i).getText()); + } + //get list of value field names as appear in data-tests-id + List<String> valueField = new ArrayList<>(); + for (int i = 0; i < valueName.size(); i++) { + valueField.add(PropertyNameBuilder.buildIComplexField(propName, valueName.get(i))); + } + return valueField; + } + + private Map<String, String> getMapOfCapPropValues(List<String> valueField, boolean isValueAssign) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Assigning values to properties of capabilities and/or collecting existing ones")); + Map<String, String> propValues = new HashMap<>(); + for (int i = 0; i < valueField.size(); i++) { + String fieldId = valueField.get(i); + if (GeneralUIUtils.getWebElementByTestID(fieldId).getAttribute("value").isEmpty() && isValueAssign) { + //add value and put into map + propValues.put(fieldId, "value" + i); + PropertiesAssignmentPage.editPropertyValue(fieldId, "value" + i); + } else { + //put existing value into map + propValues.put(fieldId, GeneralUIUtils.getWebElementByTestID(valueField.get(i)).getAttribute("value")); + } + } + return propValues; + } + + + public ImmutablePair<Integer, Integer> calcMidOfLink(ImmutablePair<Integer, Integer> location1, ImmutablePair<Integer, Integer> location2) { + int x = (location1.getLeft() + location2.getLeft()) / 2; + int y = (location1.getRight() + location2.getRight()) / 2; + + ImmutablePair<Integer, Integer> location = new ImmutablePair<>(x, y); + return location; + } + + public ImmutablePair<Integer, Integer> getElementCoordinates(String elementName) { + Object position = GeneralUIUtils.getElementPositionOnCanvas(elementName); + return converJSJsonToCoordinates(position); + } + + public ImmutablePair<Integer, Integer> getGreenDotCoordinatesOfElement(String elementName) { + Object position = GeneralUIUtils.getElementGreenDotPositionOnCanvas(elementName); + return converJSJsonToCoordinates(position); + } + + public ImmutablePair<Integer, Integer> converJSJsonToCoordinates(Object position) { + JsonElement root = new JsonParser().parse(position.toString()); + int xElement = root.getAsJsonObject().get("x").getAsInt(); + int yElement = root.getAsJsonObject().get("y").getAsInt(); + return new ImmutablePair<Integer, Integer>(xElement, yElement); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CatalogFilterTitlesEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CatalogFilterTitlesEnum.java new file mode 100644 index 0000000000..82ac5d799d --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CatalogFilterTitlesEnum.java @@ -0,0 +1,37 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum CatalogFilterTitlesEnum { + + TYPE("typeFilterTitle"), CATEGORIES("categoriesFilterTitle"), STATUS("statusFilterTitle"); + + private String value; + + public String getValue() { + return value; + } + + CatalogFilterTitlesEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CheckBoxStatusEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CheckBoxStatusEnum.java new file mode 100644 index 0000000000..7d6b3ab05d --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CheckBoxStatusEnum.java @@ -0,0 +1,50 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum CheckBoxStatusEnum { + CHECKOUT("", "checkbox-checkout"), + CHECKIN("", "checkbox-checkin"), + READY_FOR_TESTING("checkbox-readyforcertification", "checkbox-1"), + IN_TESTING("checkbox-incertification", "checkbox-2"), + WAITING_FOR_DISTRIBUTION("", "checkbox-waitingforapproval"), + DISTRIBUTION_REJECTED("", "checkbox-distributionrejected"), + DISTRIBUTION_APPROVED("", "checkbox-distributionapproved"), + CERTIFIED("checkbox-certified", "checkbox-3"), + DISTRIBUTED("checkbox-distributed", "checkbox-4"), + IN_DESIGN("checkbox-indesign", "checkbox-0"); + + private String value; + private String value2; + + public String getValue() { + return value; + } + + public String getCatalogValue() { + return value2; + } + + CheckBoxStatusEnum(String value, String value2) { + this.value = value; + this.value2 = value2; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ConnectionWizardPopUpObject.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ConnectionWizardPopUpObject.java new file mode 100644 index 0000000000..7dcbbba048 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ConnectionWizardPopUpObject.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.datatypes; + +public class ConnectionWizardPopUpObject { + + private String capabilityTypeFirstItem; + private String capabilityTypeSecondItem; + private String capabilityNameFirstItem; + private String capabilityNameSecondItem; + + public ConnectionWizardPopUpObject(String capabilityTypeFirstItem, String capabilityNameFirstItem, String capabilityTypeSecondItem, String capabilityNameSecondItem) { + this.capabilityTypeFirstItem = capabilityTypeFirstItem; + this.capabilityTypeSecondItem = capabilityTypeSecondItem; + this.capabilityNameFirstItem = capabilityNameFirstItem; + this.capabilityNameSecondItem = capabilityNameSecondItem; + } + + public String getCapabilityTypeFirstItem() { + return capabilityTypeFirstItem; + } + + public void setCapabilityTypeFirstItem(String capabilityTypeFirstItem) { + this.capabilityTypeFirstItem = capabilityTypeFirstItem; + } + + public String getCapabilityTypeSecondItem() { + return capabilityTypeSecondItem; + } + + public void setCapabilityTypeSecondItem(String capabilityTypeSecondItem) { + this.capabilityTypeSecondItem = capabilityTypeSecondItem; + } + + public String getCapabilityNameFirstItem() { + return capabilityNameFirstItem; + } + + public void setCapabilityNameFirstItem(String capabilityNameFirstItem) { + this.capabilityNameFirstItem = capabilityNameFirstItem; + } + + public String getCapabilityNameSecondItem() { + return capabilityNameSecondItem; + } + + public void setCapabilityNameSecondItem(String capabilityNameSecondItem) { + this.capabilityNameSecondItem = capabilityNameSecondItem; + } + + @Override + public String toString() { + return "ConnectionWizardPopUpObject{" + + "capabilityTypeFirstItem='" + capabilityTypeFirstItem + '\'' + + ", capabilityTypeSecondItem='" + capabilityTypeSecondItem + '\'' + + ", capabilityNameFirstItem='" + capabilityNameFirstItem + '\'' + + ", capabilityNameSecondItem='" + capabilityNameSecondItem + '\'' + + '}'; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CreateAndImportButtonsEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CreateAndImportButtonsEnum.java new file mode 100644 index 0000000000..07a3641376 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/CreateAndImportButtonsEnum.java @@ -0,0 +1,27 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum CreateAndImportButtonsEnum { + + IMPORT_VF, IMPORT_VFC, IMPORT_CP, IMPORT_VL, CREATE_VF, CREATE_SERVICE, CREATE_PRODUCT; + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/DataTestIdEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/DataTestIdEnum.java new file mode 100644 index 0000000000..7e8f93637a --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/DataTestIdEnum.java @@ -0,0 +1,840 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import org.onap.sdc.frontend.ci.tests.pages.TopSearchComponent; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public final class DataTestIdEnum { + + private DataTestIdEnum() { + } + + @AllArgsConstructor + @Getter + public enum Dashboard { + IMPORT_AREA("importButtonsArea"), + ADD_AREA("AddButtonsArea"), + BUTTON_ADD_VF("createResourceButton"), + BUTTON_ADD_SERVICE("createServiceButton"), + IMPORT_VFC("importVFCbutton"), + IMPORT_VF("importVFbutton"), + IMPORT_VFC_FILE("file-importVFCbutton"), + IMPORT_VF_FILE("file-importVFbutton"), + BUTTON_ADD_PRODUCT("createProductButton"), + BUTTON_ADD_PNF("createPNFButton"), + BUTTON_ADD_CR("createCRButton"); + + private final String value; + } + + @AllArgsConstructor + @Getter + public enum LifeCyleChangeButtons { + CREATE("create/save"), + CHECK_IN("check_in"), + SUBMIT_FOR_TESTING("submit_for_testing"), + START_TESTING("start_testing"), + ACCEPT("accept"), + CERTIFY("certify"), + CHECKOUT("check_out"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum DistributionChangeButtons { + APPROVE("approve"), + REJECT("reject"), + DISTRIBUTE("distribute"), + MONITOR("monitor"), + APPROVE_MESSAGE("checkindialog"), + RE_DISTRIBUTE("redistribute"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum InformationalArtifactsPlaceholders { + CLOUD_QUESTIONNAIRE("Cloud Questionnaire (completed)"), + FEATURES("Features"), + VENDOR_TEST_RESULT("Vendor Test Result"), + TEST_SCRIPTS("Test Scripts"), + RESOURCE_SECURITY_TEMPLATE("Resource Security Template"), + HEAT_TEMPLATE_FROM_VENDOR("HEAT Template from Vendor"), + CAPACITY("Capacity"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ModalItems { + BROWSE_BUTTON("browseButton"), + ADD("Add"), + DESCRIPTION("description"), + SUMBIT_FOR_TESTING_MESSAGE("changeLifeCycleMessage"), + OK("confirm-modal-button-ok"), + CANCEL("Cancel"), + DELETE_INSTANCE_OK("deleteInstanceModal-button-ok"), + DELETE_INSTANCE_CANCEL("deleteInstanceModal-button-cancel"), + RENAME_INSTANCE_OK("renameInstanceModal-button-ok"), + RENAME_INSTANCE_CANCEL("renameInstanceModal-button-cancel"), + UPGRADE_SERVICES_CANCEL("upgradeVspModal-close"), + UPGRADE_SERVICES_OK("upgradeVspModal-button-upgrade"), + UPDATE_SERVICES_OK("upgradeVspModal-button-update"), + UPGRADE_SERVICES_CLOSE("upgradeVspModal-button-close"), + UPGRADE_ARTIFACT_BUTTON("upgradeVspModal-button-done"), + ACCEPT_TESTING_MESSAGE("checkindialog"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum LeftPanelCanvasItems { + BLOCK_STORAGE("BlockStorage"), + CINDER_VOLUME("CinderVolume"), + COMPUTE("Compute"), + LOAD_BALANCER("LoadBalancer"), + NOVA_SERVER("NovaServer"), + OBJECT_STORAGE("ObjectStorage"), + NEUTRON_PORT("NeutronPort"), + PORT("Port"), DATABASE("Database"), + NETWORK("Network"), + CONTRAIL_PORT("ContrailPort"), + CONTRAIL_VIRTUAL_NETWORK("ContrailVirtualNetwork"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum LinkMenuItems { + LINK_ITEM_CAP_OR_REQ("req-or-cap-item"), + REQ_CAP_SELECT_DATA_TESTS_ID("value-select"); + + private final String value; + + } + + + @AllArgsConstructor + @Getter + public enum GeneralCanvasItems { + CANVAS("canvas"), + CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"), + DELETE_INSTANCE_BUTTON("deleteInstance"), + UPDATE_INSTANCE_NAME("e-sdc-small-icon-update"), + INSTANCE_NAME_FIELD("instanceName"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ResourceMetadataEnum { + RESOURCE_NAME("name"), + DESCRIPTION("description"), + CATEGORY("selectGeneralCategory"), + VENDOR_NAME("vendorName"), + VENDOR_RELEASE("vendorRelease"), + TAGS("i-sdc-tag-input"), + CONTACT_ID("contactId"), + ICON(" iconBox"), + TAGS_TABLE("i-sdc-tag-text"), + SELECT_VSP("filename"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum GeneralElementsEnum { + CREATE_BUTTON("create/save"), + CHECKIN_BUTTON("check_in"), + CHECKOUT_BUTTON("check_out"), + SUBMIT_FOR_TESTING_BUTTON("submit_for_testing"), + DELETE_VERSION_BUTTON("delete_version"), + REVERT_BUTTON("revert"), + LIFECYCLE_STATE("formlifecyclestate"), + VERSION_HEADER("versionHeader"), + OK("OK"), + UPDATE_SERVICES_BUTTON("open-upgrade-vsp-popup"), + UPLOAD_FILE_INPUT("browseButton"), + RESTORE_BUTTON("restore-component-button"), + ARCHIVE_BUTTON("archive-component-button"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ArtifactPageEnum { + ADD_DEPLOYMENT_ARTIFACT("add_artifact_btn"), + ADD_INFORMATIONAL_ARTIFACT("add-information-artifact-button"), + DOWNLOAD_ARTIFACT_ENV("download_env_"), + ADD_ANOTHER_ARTIFACT("add-another-artifact-button"), + EDIT_ARTIFACT("edit_"), //upload env file by its label(via deployment artifact view)/displayName(via Canvas) + DELETE_ARTIFACT("delete_"), + DOWNLOAD_ARTIFACT("download_"), + BROWSE_ARTIFACT("gab-"), + GET_DEPLOYMENT_ARTIFACT_DESCRIPTION("description"), + GET_INFORMATIONAL_ARTIFACT_DESCRIPTION("Description"), + OK("OK"), + TYPE("artifactType_"), + DEPLOYMENT_TIMEOUT("timeout_"), + VERSION("artifactVersion_"), + UUID("artifactUUID_"), + EDIT_PARAMETERS_OF_ARTIFACT("edit-parameters-of-"), + DELETE_PARAMETER_OF_ARTIFACT("delete-"), + ARTIFACT_NAME("artifactDisplayName_"), + UPLOAD_HEAT_ENV_PARAMETERS("uplaodEnv_"), + VERSION_ENV("artifactEnvVersion_"), + ADD_OTHER_ARTIFACT_BUTTON("//button[@class='add-button ng-scope']"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum PropertiesPageEnum { + ADD_NEW_PROPERTY("addGrey"), + EDIT_PROPERTY("edit_"), + DELETE_PROPERTY("delete_"), + DELETE_PROPERTY_POPUP("delete_property"), + PROPERTY_NAME("propertyName_"), + PROPERTY_DESCRIPTION("propertyDescription_"), + PROPERTY_TYPE("propertyType_"), + ENTRY_SCHEMA("propertySchema_"), + ADD("Add"), CANCEL("Cancel"), + DONE("Done"), + PROPERTY_ROW("propertyRow"), + SAVE("Save"), + POPUP_FORM("sdc-edit-property-container"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum PropertiesPopupEnum { + PROPERTY_NAME("propertyName"), + PROPERTY_VALUE("defaultvalue"), + PROPERTY_BOOLEAN_VALUE("booleantype"), + PROPERTY_DESCRIPTION("description"), + PROPERTY_TYPE("propertyType"), + ENTRY_SCHEMA("schema-type"), + CANCEL("Cancel"), + SAVE("Save"), + POPUP_FORM("sdc-edit-property-container"), + ADD("Add"), + DONE("Done"), + PROPERTY_RADIO_BUTTON_CONTAINER("propertyRadioButton_"), + RADIO_BUTTON_CLASS("tlv-radio-label"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum AdminPageTabs { + USER_MANAGEMENT("usermanagmenttab"), + CATEGORY_MANAGEMENT("categorymanagmenttab"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum UserManagementEnum { + SEARCH_BOX("searchbox"), + NEW_USER_FIELD("newuserId"), + ROLE_SELECT("selectrole"), + CREATE_BUTTON("creategreen"), + CLASS_USER_MANAGEMENT_TABLE("sdc-user-management-table"), + ROW_TABLE("row_"), + FIRST_NAME("firstName_"), + LAST_NAME("lastName__"), + USER_ID("userId_"), + EMAIL("email_"), + ROLE("role_"), + LAST_ACTIVE("lastActive_"), + UPDATE_ROLE("selectRole_"), + UPDATE_USER_BUTTON("updateUser_"), + SAVE_USER("save_"), + DELETE_USER("delete_"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CategoryManagement { + SERVICE_CATEGORY_HEADER("servicecategoryheader"), + RESOURCE_CATEGORY_HEADER("resourcecategoryheader"), + SERVICE_CATEGORY_LIST("servicecategory"), + RESOURCE_CATEGORY_LIST("resourcecategory"), + NEW_CATEGORY_BUTTON("newcategory"), + NEW_SUB_CATEGORY_BUTTON("newsubcategory"), + NEW_CATEGORY_NAME("i-sdc-form-input"); + + private final String value; + + } + + + @AllArgsConstructor + @Getter + public enum MainMenuButtons { + HOME_BUTTON("main-menu-button-home"), + CATALOG_BUTTON("main-menu-button-catalog"), + ONBOARD_BUTTON("main-menu-button-onboard"), + SEARCH_BOX(TopSearchComponent.SEARCH_INPUT_TEST_ID), + REPOSITORY_ICON("repository-icon"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CatalogSwitchButtons { + CATALOG_SWITCH_BUTTON("catalog-selector-button"), // get possible catalog types(active/archive) + CATALOG_ACTIVE_ITEMS("catalog-selector-0"), // select active catalog + CATALOG_ARCHIVE("catalog-selector-1"); // select archive catalog + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum MainMenuButtonsFromInsideFrame { + HOME_BUTTON("breadcrumbs-button-0"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum MenuOptionsEnum { + EDIT("Edit"), + CHECK_IN("Check in"), + CHECK_OUT("Check out"), + VIEW("View"), + SUBMIT_FOR_TEST("Submit For Test"), + ACCEPT("Accept"), + REJECT("Reject"), + START_TEST("Start test"), + DISTREBUTE("Distribute"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum StepsEnum { + GENERAL("GeneralLeftSideMenu"), + ICON("Iconstep"), + DEPLOYMENT_ARTIFACT("Deployment ArtifactLeftSideMenu"), + INFORMATION_ARTIFACT("Information ArtifactLeftSideMenu"), + PROPERTIES("PropertiesLeftSideMenu"), + COMPOSITION("CompositionLeftSideMenu"), + ACTIVITY_LOG("Activity LogLeftSideMenu"), + DEPLOYMENT_VIEW("DeploymentLeftSideMenu"), + TOSCA_ARTIFACTS("TOSCA ArtifactsLeftSideMenu"), + MONITOR("DistributionLeftSideMenu"), + MANAGEMENT_WORKFLOW("Management WorkflowLeftSideMenu"), + INPUTS("Inputs"), + HIERARCHY("Hierarchy"), + PROPERTIES_ASSIGNMENT("Properties AssignmentLeftSideMenu"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ArtifactPopup { + BROWSE("browseButton"), + FILE_UNDEFINED("fileundefined"), + ARTIFACT_DESCRIPTION("description"), + ARTIFACT_LABEL("artifactLabel"), + ARTIFACT_TYPE("artifacttype"), + ARTIFACT_TYPE_ICON("artifacttype-icon"), + OK("OK"), + SAVE("Save"), + DONE_BUTTON("Done"), + CANCEL_BUTTON("Cancel"), + URL("input[class^='i-sdc-form-input']"), + MODAL_WINDOW("sdc-add-artifact"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ServiceMetadataEnum { + SERVICE_NAME("name"), + DESCRIPTION("description"), + CATEGORY("selectGeneralCategory"), + PROJECT_CODE("projectCode"), + NAMING_POLICY("namingPolicy"), + SERVICE_FUNCTION("serviceFunction"), + TAGS("i-sdc-tag-input"), + CONTACT_ID("contactId"), + ICON(" iconBox"), + INSTANTIATION_TYPE("selectInstantiationType"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ProductMetadataEnum { + PRODUCT_NAME("name"), + FULL_NAME("fullName"), + DESCRIPTION("description"), + PROJECT_CODE("projectCode"), + TAGS("i-sdc-tag-input"), + ATT_CONTACT("attContact"), + ICON(" iconBox"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum DashboardCardEnum { + ASSET_TYPE("asset-type"), LIFECYCLE_STATE("span[class^='w-sdc-dashboard-card-info-lifecycleState']"), + INFO_NAME("div.sdc-tile-info-line"), + VERSION("div[class^='w-sdc-dashboard-card-info-user']"), + DASHBOARD_CARD("div[class^='w-sdc-dashboard-card ']"), + INFO_TITLE_XPATH("//div[contains(@class,'sdc-tile-info-line title')]"), + ASSET_TYPE_CSS("span[data-tests-id='asset-type']"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CatalogPageLeftPanelCategoryCheckbox { + GENERIC_CHECKBOX("span[data-tests-id='checkbox-resourcenewcategory.generic']"), + NETWORK_L2_3("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3']"), + NETWORK_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.networkl4+']"), + NETWORK_CONNECTIVITY("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity']"), + APPLICATION_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+']"), + DCAE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent']"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CatalogPageLeftPanelFilterTitle { + TYPE("span[data-tests-id='typeFilterTitle']"), + CATEGORIES("span[data-tests-id='categoriesFilterTitle']"), + STATUS("span[data-tests-id='statusFilterTitle']"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CatalogPageLeftPanelSubCategoryCheckbox { + COMMON_NETWORK_RESOURCES("span[data-tests-id='checkbox-resourcenewcategory.networkl4+.commonnetworkresources']"), + ROUTER("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.router']"), + WAN_CONNECTORS("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.wanconnectors']"), + LAN_CONNECTORS("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.lanconnectors']"), + INFRASTRUCTURE_NETWORK_L2_3("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.infrastructure']"), + GATEWAY("span[data-tests-id='checkbox-resourcenewcategory.networkl2-3.gateway']"), + NETWORK_ELEMENTS("span[data-tests-id='checkbox-resourcenewcategory.generic.networkelements']"), + ABSTRACT("span[data-tests-id='checkbox-resourcenewcategory.generic.abstract']"), + RULES("span[data-tests-id='checkbox-resourcenewcategory.generic.rules']"), + DATABASE("span[data-tests-id='checkbox-resourcenewcategory.generic.database']"), + INFRASTRUCTERE_GENERIC("span[data-tests-id='checkbox-resourcenewcategory.generic.infrastructure']"), + VIRTUAL_LINKS("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity.virtuallinks']"), + CONNECTION_POINTS("span[data-tests-id='checkbox-resourcenewcategory.networkconnectivity.connectionpoints']"), + APPLICATION_SERVER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.applicationserver']"), + CALL_CONTROL("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.callcontrol']"), + MEDIASERVERS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.mediaservers']"), + WEBSERVER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.webserver']"), + LOAD_BALANCER("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.loadbalancer']"), + BORDER_ELEMENT("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.borderelement']"), + DATABASE_APPLIVATION_L4_PLUS("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.database']"), + FIREWALL("span[data-tests-id='checkbox-resourcenewcategory.applicationl4+.firewall']"), + DATABASE_DCAE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.database']"), + POLICY("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.policy']"), + MICROSERVICE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.microservice']"), + SOURCE("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.source']"), + COLLECTOR("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.collector']"), + UTILITY("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.utility']"), + ANALYTICS("span[data-tests-id='checkbox-resourcenewcategory.dcaecomponent.analytics']"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CompositionScreenEnum { + CHANGE_VERSION("changeVersion", Collections.emptyList()), + DEPLOYMENT_ARTIFACT_TAB("deployment-artifact-tab", Collections.singletonList("Deployment Artifacts")), + ADD_ARTIFACT("add_Artifact_Button", Collections.emptyList()), + SEARCH_ASSET("searchAsset-input", Arrays.asList()), + PROPERTIES_AND_ATTRIBUTES_TAB("properties-and-attributes-tab", Collections.emptyList()), + MENU_INPUTS("sub-menu-button-inputs", Collections.emptyList()), + MENU_ONBOARD("sub-menu-button-onboard", Collections.emptyList()), + MENU_HOME("sub-menu-button-home", Collections.emptyList()), + MENU_PROPERTIES_ASSIGNMENT("sub-menu-button-properties assignment", Collections.emptyList()), + MENU_TRIANGLE_DROPDOWN("triangle-dropdown", Collections.emptyList()), + ARTIFACTS_LIST("artifactName", Collections.emptyList()), + INFORMATION_ARTIFACTS("button[tooltip-content='Information Artifacts']", + Collections.singletonList("Informational Artifacts")), + API("button[tooltip-content='API']", Collections.singletonList("API Artifacts")), + INFORMATION("button[tooltip-content='Information']", Arrays.asList("General Info", "Additional Information", "Tags")), + COMPOSITION("button[tooltip-content='Composition']", Collections.singletonList("Composition")), + INPUTS("button[tooltip-content='Inputs']", Collections.singletonList("")), + REQUIREMENTS_AND_CAPABILITIES("button[tooltip-content='Requirements and Capabilities']", + Collections.emptyList()), + INFORMATION_TAB("information-tab", Collections.emptyList()), + CUSTOMIZATION_UUID("rightTab_customizationModuleUUID", Collections.emptyList()); + + private final String value; + private final List<String> title; + + } + + @AllArgsConstructor + @Getter + public enum ToscaArtifactsScreenEnum { + TOSCA_MODEL("download-Tosca Model"), + TOSCA_TEMPLATE("download-Tosca Template"), + ARTIFACT_VERSION("version-"), + ARTIFACT_NAME("name-"), + ARTIFACT_TYPE("type-"), + ARTIFACT_DETAILS("details-"), + DOWNLOAD_ARTIFACT("download-"), + DOWNLOAD_CSAR("download-Tosca Model"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum InformationalArtifactsService { + AFFINITY_RULES("artifact_Display_Name-Affinity Rules"), + CONTROL_LOOP_FUNCTIONS("artifact_Display_Name-Control Loop Functions"), + DEPLOYMENT_VOTING_RECORD("artifact_Display_Name-Deployment Voting Record"), + DIMENSIONING_INFO("artifact_Display_Name-Dimensioning Info"), + DISTRIBUTION_INSTRUCTION("artifact_Display_Name-Distribution Instructions"), + ENGINEERING_RULES("artifact_Display_Name-Engineering Rules (ERD)"), + OPERATIONAL_POLICES("artifact_Display_Name-Operational Policies"), + SERVICE_ARTIFACT_PLAN("artifact_Display_Name-Service Artifact Plan"), + SERVICE_QUESTIONNAIRE("artifact_Display_Name-Service Questionnaire"), + SERVICE_SECURITY_TEMPLATE("artifact_Display_Name-Service Security Template"), + SERVICE_SPECIFIC_POLICIES("artifact_Display_Name-Service-specific Policies"), + SUMMARY_OF_IMPACTS_TO_ECOMP("artifact_Display_Name-Summary of impacts to ECOMP elements,OSSs, BSSs"), + TD_CERTIFICATION_TEST_RESULTS("artifact_Display_Name-TD Certification Test Results"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum APIArtifactsService { + CONFIGURATION("artifact_Display_Name-Configuration"), + INSTANTIATION("artifact_Display_Name-Instantiation"), + LOGGING("artifact_Display_Name-Logging"), + MONITORING("artifact_Display_Name-Monitoring"), + REPORTING("artifact_Display_Name-Reporting"), + TESTING("artifact_Display_Name-Testing"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum DeploymentArtifactCompositionRightMenu { + ARTIFACT_NAME("artifactName-"), + ARTIFACT_DISPLAY_NAME("artifact_Display_Name-"), + DOWNLOAD("download_"), + DELETE("delete_"), + ADD_ARTIFACT_BUTTON("add_Artifact_Button"), + EDIT_PARAMETERS_OF_ARTIFACT("edit-parameters-of-"), + ARTIFACT_ITEM("artifact-item-"), + ARTIFACT_ENV("heat_env_"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum InputsScreenService { + ADD_SELECTED_INPUTS_BTN("add-inputs-to-service-button"), + VF_INSTANCE_ROWS("expand-collapse[expanded-selector^='.vf-instance-list.']"), + VF_INSTANCE_ROW_NAME("span[class^='title-text']"), + VF_INSTANCE_INPUTS("div[class^='vf-instance-list ']"), + VF_INSTANCE_INPUT("div[class^='input-row ng-scope']"), + VF_INSTNCE_PROPERTY_NAME("div[class^='title-text']"), + INPUT_CHECKBOX("span[class^='tlv-checkbox-label']"), + SERVICE_INPUT_ROW("div[class^='service-input-row input-row']"), + DELETE_INPUT_BTN("span[class$='remove-input-icon']"), + RESOURCE_INSTANCE_PROPERTY_NAME("propertyName_"), + RESOURCE_INSTANCE_PROPERTY_TYPE("propertyType_"), + RESOURCE_INSTANCE_PROPERTY_CHECKBOX("propertyCheckbox_"), + SERVICE_INPUTS_DELETE_BUTTON("deleteInput_"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum DeploymentScreen { + MODULES("span[class^='expand-collapse-title-text']"), + MEMBERS("div[class^='expand-collapse-sub-title']"), + PROPERTIES("list-of-Properties"), + ARTIFACTS("list-of-Artifacts"), + BUTTON_PROPERTIES("div[data-tests-id='list-of-Properties'] span[class^='hand']"), + BUTTON_ARTIFACTS("div[data-tests-id='list-of-Artifacts'] span[class^='hand']"), + PROPERTY_NAMES("div[data-tests-id='selected-module-property-name'] span"), + PROPERTY_TYPES("selected-module-property-type"), + PROPERTY_SCHEMA_TYPE("selected-module-property-schema-type"), + ARTIFACT_NAME("selected-module-artifact-name"), + ARTIFACT_UUID("selected-module-artifact-uuid"), + ARTIFACT_VERSION("selected-module-artifact-version"), + PENCIL_ICON("edit-name-popover-icon"), + MODULE_NAME("selected-module-name"), + MODULE_ID("selected-module-group-uuid"), + RESOURCE_NAME_ON_POPOVER("popover-vfinstance-name"), + MODULE_NAME_ON_POPOVER("popover-module-name"), + NAME_INPUT("popover-heat-name"), + SAVE("popover-save-button"), + CANCEL("popover-close-button"), + X_BUTTON("popover-x-button"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum PropertiesAssignmentScreen { + PROPERTIES_TAB("Properties"), + INPUTS_TAB("Inputs"), + COMPOSITION_TAB("Composition"), + PROPERTY_STRUCTURE_TAB("Property Structure"), + SEARCH_BOX("search-box"), + FILTER_BOX("filter-box"), + SAVE_BUTTON("properties-save-button"), + DISCARD_BUTTON("properties-reverse-button"), + DECLARE_BUTTON("declare-button"), + SEARCH_BUTTON("search-button"), + FILTER_BUTTON("filter-button"), + EXPAND_BUTTON("expand-"), + CLEAR_FILTER_BUTTON("clear-filter-button"), + INPUT_DELETE_BUTTON("delete-input-button"), + INPUT_DELETE_DIALOG_DELETE("Delete"), + INPUT_DELETE_DIALOG_CLOSE("Close"), + SAVE_DIALOG_CANCEL("id-button-cancel"), + SAVE_DIALOG_DISCARD("id-button-discard"), + SAVE_DIALOG_SAVE("id-button-save"), + PROPERTY_KEY_FIELD_PREFIX("value-prop-key-"), + PROPERTY_VALUE_FIELD_PREFIX("value-prop-"), + INPUT_VALUE_FIELD_PREFIX("value-input-"), + POPUP_VALUE_FIELD_PREFIX("edit-button-prop-"), + ADD_TO_LIST_BUTTON("add-to-list-"), + DELETE_FROM_LIST_BUTTON("delete-from-list-"), + FILTER_CHECKBOX_ALL("filter-checkbox-all"), + FILTER_CHECKBOX_CP("filter-checkbox-cp"), + FILTER_CHECKBOX_VFC("filter-checkbox-vfc"), + FILTER_CHECKBOX_VL("filter-checkbox-vl"), + FILTER_APPLY_BUTTON("filter-apply-button"), + FILTER_CLOSE_BUTTON("filter-close-button"), + FILTER_SET_BUTTON("filter-set-button"), + PROPERTY_NAME_COLUMN("property-name"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ImportVfRepository { + SEARCH("onboarding-search-input"), + IMPORT_VSP("import-csar"), + DOWNLOAD_CSAR("download-csar"), + UPDATE_VSP("update-csar"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum EnvParameterView { + SEARCH_ENV_PARAM_NAME("search-env-param-name"), + ENV_CURRENT_VALUE("value-field-of-"), //value-field-of-oam_volume_name_0 - parameter name + ENV_DEFAULT_VALUE("default-value-of-"); // default-value-of-vnf_name + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum ComplexServiceAmdocs { + CREATE_BUTTON("Create"), + DELETE_COMPONENT("deleteInstance"), + PATH_LIST_BUTTON("pathsListMenuItem"), + UPDATE_VF("create/save"), + PATH_LIST_NAME("path-name"), + PATH_LIST_EDIT("update-service-path-btn"), + PATH_LIST_DELETE("delete-service-path-btn"), + CREATE_PATH_MENU_BUTTON("createPathMenuItem"), + PATH_NAME("pathName"), + PATH_PROTOCOL("pathProtocol"), + PATH_PORT_NUMBER("pathPortNumbers"), + PATH_MENU_BUTTON("pathsMenuBtn"), + SAVE("Save"), + SEARCH("expandable-input-closed"), + LINK_SOURCE("linkSrc"), + LINK_SOURCE_CP("linkSrcCP"), + LINK_TARGET("linkTarget"), + LINK_TARGET_CP("linkTargetCP"), + SERVICE_PATH_SELECTOR("service-path-selector"), + SUBMIT_FOR_TESTING("submit_for_testing"), + CHANGE_LIFE_CYCLE_MESSAGE("changeLifeCycleMessage"), + REMOVE_LINK("removeLnk"), + OK("OK"), + ONBOARD_CATALOG("onboard-onboard-tab"), + CLOSE("Close"), + HOME_FROM_COMPOSITION("breadcrumbs-button-0"), + NEW_VSP_VERSION_DESCRIPTION("new-version-description"), + SUBMIT_NEW_VSP_VERSION_DESCRIPTION("form-submit-button"), + EXTEND_BUTTON("extendPathlnk"); + + private final String value; + + } + + + @AllArgsConstructor + @Getter + public enum PortMirroring { + COLLECTOR_NODE("collector_node"), + EQUIP_MODEL("equip_model"), + EQUIP_VENDOR("equip_vendor"), + PMC_NAME_IN_PALLETE("Port Mirroring Configuration"), + PMCP_NAME_IN_PALLETE("Port Mirroring Configuration By Policy"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CompositionRightPanelGeneralInfo { + TYPE("rightTab_componentType"), + RESOURCE_TYPE("rightTab_resourceType"), + SELECT_VERSION("changeVersion"), + CATEGORY("rightTab_category"), + SUB_CATEGORY("rightTab_subCategory"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum CompositionRightPanel { + COMPONENT_TITLE("selectedCompTitle"), + REQS_AND_CAPS_TAB("requirements-and-capabilities"), + EDIT_PENCIL("editPencil"), + INSTANCE_NAME_TEXTBOX("instanceName"), + DELETE_ITEM("deleteInstance"), + REQS_AND_CAPS_TAB_XPATH("//button[@tooltip-content='Requirements and Capabilities']"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum VspValidationPage { + VSP_VALIDATION_PAGE_NAVBAR("navbar-group-item-SOFTWARE_PRODUCT_VALIDATION"), + VSP_VALIDATION_PAGE_BREADCRUMBS("sub-menu-button-validation"), + VSP_VALIDATION_PAGE_PROCEED_TO_INPUTS_BUTTON("go-to-vsp-validation-inputs"), + VSP_VALIDATION_PAGE_PROCEED_TO_SETUP_BUTTON("go-to-vsp-validation-setup"), + VSP_VALIDATION_PAGE_INPUT("%s_%s_input"), + VSP_VALIDATION_PAGE_PROCEED_TO_RESULTS_BUTTON("proceed-to-validation-results-btn"), + VSP_VALIDATION_PAGE_COMPLIANCE_CHECKBOX_TREE("vsp-validation-compliance-checks-checkbox-tree"), + VSP_VALIDATION_PAGE_CERTIFICATION_CHECKBOX_TREE("vsp-validation-certifications-query-checkbox-tree"); + + private final String value; + + } + + @AllArgsConstructor + @Getter + public enum VspValidationResultsPage { + VSP_VALIDATION_RESULTS_PAGE_NAVBAR("navbar-group-item-SOFTWARE_PRODUCT_VALIDATION_RESULTS"), + VSP_VALIDATION_RESULTS_PAGE_BREADCRUMBS("sub-menu-button-validation results"); + + private final String value; + + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ErrorMessageProperties.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ErrorMessageProperties.java new file mode 100644 index 0000000000..30bc6bdb76 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ErrorMessageProperties.java @@ -0,0 +1,53 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public class ErrorMessageProperties { + + private String messageId; + private String code; + + public ErrorMessageProperties() { + + } + + public ErrorMessageProperties(String messageId, String code) { + this.messageId = messageId; + this.code = code; + } + + public String getMessageId() { + return messageId; + } + + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/GeneralCanvasItemsEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/GeneralCanvasItemsEnum.java new file mode 100644 index 0000000000..d480585f4a --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/GeneralCanvasItemsEnum.java @@ -0,0 +1,38 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum GeneralCanvasItemsEnum { + CANVAS("canvas"), + CANVAS_RIGHT_PANEL("w-sdc-designer-sidebar-head"), + DELETE_INSTANCE_BUTTON("deleteInstance"); + + private String value; + + public String getValue() { + return value; + } + + GeneralCanvasItemsEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/HeatAndHeatEnvNamesPair.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/HeatAndHeatEnvNamesPair.java new file mode 100644 index 0000000000..b1aff3dc20 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/HeatAndHeatEnvNamesPair.java @@ -0,0 +1,62 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +import java.io.File; + +public class HeatAndHeatEnvNamesPair { + + private File heatFileName; + private File heatEnvFileName; + + public HeatAndHeatEnvNamesPair() { + super(); + } + + public HeatAndHeatEnvNamesPair(File heatFileName, File heatEnvFileName) { + super(); + this.heatFileName = heatFileName; + this.heatEnvFileName = heatEnvFileName; + } + + public File getHeatFileName() { + return heatFileName; + } + + public void setHeatFileName(File heatFileName) { + this.heatFileName = heatFileName; + } + + public File getHeatEnvFileName() { + return heatEnvFileName; + } + + public void setHeatEnvFileName(File heatEnvFileName) { + this.heatEnvFileName = heatEnvFileName; + } + + @Override + public String toString() { + return "HeatHeatEnvNamesPair [heatFileName=" + heatFileName + ", heatEnvFileName=" + heatEnvFileName + "]"; + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/HeatWithParametersDefinition.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/HeatWithParametersDefinition.java new file mode 100644 index 0000000000..df4bf3afcf --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/HeatWithParametersDefinition.java @@ -0,0 +1,101 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; + +import java.util.List; + +public class HeatWithParametersDefinition { + + private String heatLabel; + private String heatEnvLabel; + private String heatArtifactType; + private String heatEnvArtifactType; + private String heatArtifactDisplayName; + private List<HeatParameterDataDefinition> heatParameterDefinition; + + public HeatWithParametersDefinition(String heatLabel, String heatEnvLabel, String heatArtifactType, String heatEnvArtifactType, String heatArtifactDisplayName, List<HeatParameterDataDefinition> heatParameterDefinition) { + super(); + this.heatLabel = heatLabel; + this.heatEnvLabel = heatEnvLabel; + this.heatArtifactType = heatArtifactType; + this.heatEnvArtifactType = heatEnvArtifactType; + this.heatArtifactDisplayName = heatArtifactDisplayName; + this.heatParameterDefinition = heatParameterDefinition; + } + + public String getHeatArtifactDisplayName() { + return heatArtifactDisplayName; + } + + public void setHeatArtifactDisplayName(String heatArtifactDisplayName) { + this.heatArtifactDisplayName = heatArtifactDisplayName; + } + + public String getHeatLabel() { + return heatLabel; + } + + public void setHeatLabel(String heatLabel) { + this.heatLabel = heatLabel; + } + + public String getHeatEnvLabel() { + return heatEnvLabel; + } + + public void setHeatEnvLabel(String heatEnvLabel) { + this.heatEnvLabel = heatEnvLabel; + } + + public String getHeatArtifactType() { + return heatArtifactType; + } + + public void setHeatArtifactType(String heatArtifactType) { + this.heatArtifactType = heatArtifactType; + } + + public String getHeatEnvArtifactType() { + return heatEnvArtifactType; + } + + public void setHeatEnvArtifactType(String heatEnvArtifactType) { + this.heatEnvArtifactType = heatEnvArtifactType; + } + + public List<HeatParameterDataDefinition> getHeatParameterDefinition() { + return heatParameterDefinition; + } + + public void setHeatParameterDefinition(List<HeatParameterDataDefinition> heatParameterDefinition) { + this.heatParameterDefinition = heatParameterDefinition; + } + + @Override + public String toString() { + return "HeatWithParametersDefinition [heatLabel=" + heatLabel + ", heatEnvLabel=" + heatEnvLabel + ", heatArtifactType=" + heatArtifactType + ", heatEnvArtifactType=" + heatEnvArtifactType + ", heatArtifactDisplayName=" + + heatArtifactDisplayName + ", heatParameterDefinition=" + heatParameterDefinition + "]"; + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/LifeCycleStateEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/LifeCycleStateEnum.java new file mode 100644 index 0000000000..4e8dcee546 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/LifeCycleStateEnum.java @@ -0,0 +1,47 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum LifeCycleStateEnum { + + CHECKOUT("IN DESIGN CHECK OUT"), + CHECKIN("IN DESIGN CHECK IN"), + READY_FOR_TESTING("READY FOR TESTING"), + IN_TESTING("IN TESTING"), + WAITING_FOR_DISTRIBUTION("WAITING FOR DISTRIBUTION"), + DISTRIBUTION_REJECTED("DISTRIBUTION REJECTED"), + DISTRIBUTION_APPROVED("DISTRIBUTION APPROVED"), + CERTIFIED("CERTIFIED"), + DISTRIBUTED("DISTRIBUTED"), + IN_DESIGN("IN DESIGN"); + + private String value; + private String value2; + + public String getValue() { + return value; + } + + LifeCycleStateEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/MenuOptionsEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/MenuOptionsEnum.java new file mode 100644 index 0000000000..fd2b7f23a6 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/MenuOptionsEnum.java @@ -0,0 +1,37 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum MenuOptionsEnum { + + EDIT("Edit"), CHECK_IN("Check in"), CHECK_OUT("Check out"), VIEW("View"), SUBMIT_FOR_TEST("Submit For Test"), ACCEPT("Accept"), REJECT("Reject"), START_TEST("Start test"), DISTREBUTE("Distribute"); + + private String value; + + public String getValue() { + return value; + } + + MenuOptionsEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PortMirrioringConfigurationObject.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PortMirrioringConfigurationObject.java new file mode 100644 index 0000000000..2940e6d798 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PortMirrioringConfigurationObject.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.datatypes; + +import org.openecomp.sdc.be.model.Service; + +import java.util.HashMap; +import java.util.Map; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; + +public class PortMirrioringConfigurationObject { + + private ServiceReqDetails serviceReqDetails; + private String vmmeSourceName; + private String vprobeSourceName; + private CanvasManager canvasManager; + private CanvasElement serviceElementVmmeSourceName; + private CanvasElement serviceElementVprobeCollector; + private CanvasElement portMirroringConfigurationElement; + private Service service; + private Service serviceContainerVmme_Source; + private Service serviceContainerVprobe_Collector; + private Map<String, String> capPropValues = new HashMap<>(); + + public Map<String, String> getCapPropValues() { + return capPropValues; + } + + public void setCapPropValues(Map<String, String> capPropValues) { + this.capPropValues = capPropValues; + } + + + public PortMirrioringConfigurationObject(ServiceReqDetails serviceReqDetails, String vmmeSourceName, String vprobeSourceName, + CanvasManager canvasManager, CanvasElement serviceElementVmmeSourceName, + CanvasElement serviceElementVprobeCollector, Service service, CanvasElement portMirroringConfigurationElement, + Service serviceContainerVmme_Source, Service serviceContainerVprobe_Collector) { + this.serviceReqDetails = serviceReqDetails; + this.vmmeSourceName = vmmeSourceName; + this.vprobeSourceName = vprobeSourceName; + this.canvasManager = canvasManager; + this.serviceElementVmmeSourceName = serviceElementVmmeSourceName; + this.serviceElementVprobeCollector = serviceElementVprobeCollector; + this.service = service; + this.portMirroringConfigurationElement = portMirroringConfigurationElement; + this.serviceContainerVmme_Source = serviceContainerVmme_Source; + this.serviceContainerVprobe_Collector = serviceContainerVprobe_Collector; + } + + public Service getServiceContainerVmme_Source() { + return serviceContainerVmme_Source; + } + + public Service getServiceContainerVprobe_Collector() { + return serviceContainerVprobe_Collector; + } + + public CanvasElement getPortMirroringConfigurationElement() { + return portMirroringConfigurationElement; + } + + public ServiceReqDetails getServiceReqDetails() { + return serviceReqDetails; + } + + public String getVmmeSourceName() { + return vmmeSourceName; + } + + public String getVprobeSourceName() { + return vprobeSourceName; + } + + public CanvasManager getCanvasManager() { + return canvasManager; + } + + public CanvasElement getServiceElementVmmeSourceName() { + return serviceElementVmmeSourceName; + } + + public CanvasElement getServiceElementVprobeCollector() { + return serviceElementVprobeCollector; + } + + public Service getService() { + return service; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PortMirroringEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PortMirroringEnum.java new file mode 100644 index 0000000000..ba3ee2348b --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PortMirroringEnum.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.datatypes; + +public enum PortMirroringEnum { + + PMC_ELEMENT_IN_PALLETE("Port Mirroring Configuration"), + PMCP_ELEMENT_IN_PALLETE("Port Mirroring Configuration By Policy"), + PM_REQ_TYPE("org.openecomp.capabilities.PortMirroring"), + PMC_SOURCE_CAP("Port Mirroring Configuration 0: source: [1, UNBOUNDED]"), + PMC1_SOURCE_CAP("Port Mirroring Configuration 1: source: [1, UNBOUNDED]"), + PMCP_SOURCE_CAP("Port Mirroring Configuration By Policy 0: source: [1, UNBOUNDED]"), + PMCP1_SOURCE_CAP("Port Mirroring Configuration By Policy 1: source: [1, UNBOUNDED]"), + PMC_COLLECTOR_CAP("Port Mirroring Configuration 0: collector: [1, 1]"), + CISCO_VENDOR_NAME("CISCO"), + CISCO_VENDOR_MODEL_NUMBER("4500x"), + APCON1_VENDOR_NAME("APCON1"), + APCON1_VENDOR_MODEL_NUMBER("Test_APCON1"), + APCON2_VENDOR_NAME("APCON2"), + APCON2_VENDOR_MODEL_NUMBER("Test_APCON2"), + VMME_ZIP("2016-227_vmme_vmme_30_1610_e2e.zip"), + VPROBE_ZIP("vProbe_2017-10-22_07-24.zip"), + SERVICE_PROXY_TYPE("Service Proxy"), + SERVICE_TYPE("transport"), + TYPE("Resource"), + RESOURCE_TYPE("Configuration"), + CATEGORY("Configuration"), + SUB_CATEGORY("Configuration"), + NETWORK_ROLE_XPATH("//input[@name='network_role']"), + NFC_TYPE_XPATH("//input[@name='nfc_type']"), + PPS_CAPACITY_XPATH("//input[@name='pps_capacity']"), + NF_TYPE_XPATH("//input[@name='nf_type']"), + NETWORK_ROLE_VALUE("NETWORK ROLE TEXT"), + NFC_TYPE_VALUE("NFC TYPE TEXT"), + PPS_CAPACITY_VALUE("PPS CAPACITY TEXT"), + NF_TYPE_VALUE("NF TYPE TEXT"), + PMCP_NEWNAME("NewPMCP_Name"); + + + private String value; + + public String getValue() { + return value; + } + + PortMirroringEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PropertyInfo.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PropertyInfo.java new file mode 100644 index 0000000000..b7655ddebf --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/PropertyInfo.java @@ -0,0 +1,76 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +import org.onap.sdc.backend.ci.tests.datatypes.enums.PropertyTypeEnum; + +public class PropertyInfo { + + public PropertyInfo() { + super(); + } + + public PropertyInfo(PropertyTypeEnum prop) { + super(); + this.name = prop.getName(); + this.value = prop.getValue(); + this.type = prop.getType(); + this.description = prop.getDescription(); + } + + private String name; + private String value; + private String type; + private String description; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ResourceCategoriesNameEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ResourceCategoriesNameEnum.java new file mode 100644 index 0000000000..b0b5d83dd3 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ResourceCategoriesNameEnum.java @@ -0,0 +1,45 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum ResourceCategoriesNameEnum { + + GENERIC("checkbox-resourcenewcategory.generic"), NETWORK_CONNECTIVITY("checkbox-resourcenewcategory.networkconnectivity"), NETWORK_ELEMENTS("checkbox-resourcenewcategory.generic.networkelements"), + ABSTRACT("checkbox-resourcenewcategory.generic.abstract"), DATABASE_GENERIC("checkbox-resourcenewcategory.generic.database"), INFRASTRUCTURE("checkbox-resourcenewcategory.generic.infrastructure"), + VIRTUAL_LINKS("checkbox-resourcenewcategory.networkconnectivity.virtuallinks"), CONNECTION_POINTS("checkbox-resourcenewcategory.networkconnectivity.connectionpoints"), NETWORKL4("checkbox-resourcenewcategory.networkl4+"), + COMMON_NETWORK_RESOURCES("checkbox-resourcenewcategory.networkl4+.commonnetworkresources"), APPLICATIONL4("checkbox-resourcenewcategory.applicationl4+"), WEB_SERVER("checkbox-resourcenewcategory.applicationl4+.webserver"), + APPLICATION_SERVER("checkbox-resourcenewcategory.applicationl4+.applicationserver"), CALL_CONTROL("checkbox-resourcenewcategory.applicationl4+.callcontrol"), BORDER_ELEMENT("checkbox-resourcenewcategory.applicationl4+.borderelement"), + MEDIA_SERVERS("checkbox-resourcenewcategory.applicationl4+.mediaservers"), DATABASE("checkbox-resourcenewcategory.applicationl4+.database"), FIREWALL("checkbox-resourcenewcategory.applicationl4+.firewall"), + LOAD_BALANCER("checkbox-resourcenewcategory.applicationl4+.loadbalancer"), NETWORK_L23("checkbox-resourcenewcategory.networkl2-3"), Router("checkbox-resourcenewcategory.networkl2-3.router"), + WAN_Connectors("checkbox-resourcenewcategory.networkl2-3.wanconnectors"), LAN_CONNECTORS("checkbox-resourcenewcategory.networkl2-3.lanconnectors"), GATEWAY("checkbox-resourcenewcategory.networkl2-3.gateway"), + INFRASTRUCTUREL23("checkbox-resourcenewcategory.networkl2-3.infrastructure"); + + private String value; + + public String getValue() { + return value; + } + + ResourceCategoriesNameEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ServiceCategoriesNameEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ServiceCategoriesNameEnum.java new file mode 100644 index 0000000000..989a4eaee1 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ServiceCategoriesNameEnum.java @@ -0,0 +1,36 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum ServiceCategoriesNameEnum { + + NETWORK_L13("checkbox-servicenewcategory.networkl1-3"), VOIPCALL_CONTROL("checkbox-servicenewcategory.voipcallcontrol"), NETWORKL4("checkbox-servicenewcategory.networkl4+"), MOBILITY("checkbox-servicenewcategory.mobility"); + + private String value; + + public String getValue() { + return value; + } + + private ServiceCategoriesNameEnum(String value) { + this.value = value; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ServiceContainer.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ServiceContainer.java new file mode 100644 index 0000000000..d39d6f1a74 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/ServiceContainer.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.datatypes; + +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; + +public class ServiceContainer { + private Service service; + private Resource resource; + private VendorSoftwareProductObject vendorSoftwareProductObject; + private VendorLicenseModel vendorLicenseModel; + + public ServiceContainer(Service service, Resource resource, VendorSoftwareProductObject vendorSoftwareProductObject, VendorLicenseModel vendorLicenseModel) { + this.service = service; + this.resource = resource; + this.vendorSoftwareProductObject = vendorSoftwareProductObject; + this.vendorLicenseModel = vendorLicenseModel; + } + + public Service getService() { + return service; + } + + public void setService(Service service) { + this.service = service; + } + + public Resource getResource() { + return resource; + } + + public void setResource(Resource resource) { + this.resource = resource; + } + + public VendorSoftwareProductObject getVendorSoftwareProductObject() { + return vendorSoftwareProductObject; + } + + public void setVendorSoftwareProductObject(VendorSoftwareProductObject vendorSoftwareProductObject) { + this.vendorSoftwareProductObject = vendorSoftwareProductObject; + } + + public VendorLicenseModel getVendorLicenseModel() { + return vendorLicenseModel; + } + + public void setVendorLicenseModel(VendorLicenseModel vendorLicenseModel) { + this.vendorLicenseModel = vendorLicenseModel; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/TopMenuButtonsEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/TopMenuButtonsEnum.java new file mode 100644 index 0000000000..88e86f2e90 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/TopMenuButtonsEnum.java @@ -0,0 +1,40 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum TopMenuButtonsEnum { + + HOME("main-menu-button-home"), + CATALOG("main-menu-button-catalog"), + ON_BOARDING("main-menu-button-onboard"); + + private String value; + private String value2; + + public String getButton() { + return value; + } + + TopMenuButtonsEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/TypesEnum.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/TypesEnum.java new file mode 100644 index 0000000000..25bdade893 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/TypesEnum.java @@ -0,0 +1,36 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public enum TypesEnum { + + RESOURCE("checkbox-resource"), VF("checkbox-vf"), VFC("checkbox-vfc"), PNF("checkbox-pnf"), CP("checkbox-cp"), VL("checkbox-vl"), SERVICE("checkbox-service"), PRODUCT("checkbox-product"); + private String value; + + public String getValue() { + return value; + } + + TypesEnum(String value) { + this.value = value; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/UserCredentials.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/UserCredentials.java new file mode 100644 index 0000000000..4678d7aa15 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/UserCredentials.java @@ -0,0 +1,50 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +import org.openecomp.sdc.be.model.User; + +public class UserCredentials extends User { + + private String password; + + public UserCredentials(String userId, String password, String firstname, String lastname, String role) { + super(); + setUserId(userId); + this.password = password; + setFirstName(firstname); + setLastName(lastname); + setRole(role); + } + + public UserCredentials() { + super(); + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/UserManagementTab.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/UserManagementTab.java new file mode 100644 index 0000000000..8fb0512d92 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/UserManagementTab.java @@ -0,0 +1,118 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class UserManagementTab { + + public void searchUser(String searchCriterion) { + ExtentTestActions.log(Status.INFO, "Searching a user by the value : " + searchCriterion); + WebElement searchBoxWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.SEARCH_BOX.getValue()); + searchBoxWebElement.clear(); + searchBoxWebElement.sendKeys(searchCriterion); + GeneralUIUtils.ultimateWait(); + } + + public void setNewUserBox(String user) { + ExtentTestActions.log(Status.INFO, "Inserting userid " + user); + WebElement createNewUserWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.NEW_USER_FIELD.getValue()); + createNewUserWebElement.clear(); + createNewUserWebElement.sendKeys(user); + GeneralUIUtils.ultimateWait(); + } + + public void selectUserRole(UserRoleEnum userRole) { + String role = userRole.name().toLowerCase(); + ExtentTestActions.log(Status.INFO, "Selecting role " + userRole.name()); + GeneralUIUtils.getSelectList(role, DataTestIdEnum.UserManagementEnum.ROLE_SELECT.getValue()); + } + + public void updateUserRole(UserRoleEnum userRole, int rowIndx) { + String role = userRole.name().toLowerCase(); + ExtentTestActions.log(Status.INFO, "Updating the user role to " + userRole.name()); + GeneralUIUtils.getSelectList(role, DataTestIdEnum.UserManagementEnum.UPDATE_ROLE.getValue() + rowIndx); + } + + public void clickCreateButton() { + ExtentTestActions.log(Status.INFO, "Clicking on 'Create' button."); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.CREATE_BUTTON.getValue()); + } + + public WebElement getRow(int index) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.ROW_TABLE.getValue() + index); + } + + public WebElement getFirstName(int index) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.FIRST_NAME.getValue() + index); + } + + public WebElement getLastName(int index) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.LAST_NAME.getValue() + index); + } + + public WebElement getUserId(int index) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.USER_ID.getValue() + index); + } + + public WebElement getEmail(int index) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.EMAIL.getValue() + index); + } + + public WebElement getRole(int index) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.ROLE.getValue() + index); + } + + public WebElement getLastActive(int index) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.UserManagementEnum.LAST_ACTIVE.getValue() + index); + } + + public void updateUser(int index) { + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.UPDATE_USER_BUTTON.getValue() + index); + } + + public void deleteUser(int index) { + ExtentTestActions.log(Status.INFO, "Deleting the user in row " + (index + 1)); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.DELETE_USER.getValue() + index); + //GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickOKButton(); + } + + public void saveAfterUpdateUser(int index) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.UserManagementEnum.SAVE_USER.getValue() + index); + } + + public List<WebElement> getAllRowsDisplayed() { + return GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.UserManagementEnum.ROW_TABLE.getValue()); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/VFCArtifact.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/VFCArtifact.java new file mode 100644 index 0000000000..cb29351662 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/VFCArtifact.java @@ -0,0 +1,71 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.datatypes; + +public class VFCArtifact { + + private String artifactUUID; + private String artifactVersion; + private String artifactname; + private String artifacttype; + + + public VFCArtifact(String artifactName, String artifactType, String uuid, String version) { + artifactname = artifactName; + artifactUUID = uuid; + artifactVersion = version; + artifacttype = artifactType; + } + + public String getArtifactUUID() { + return artifactUUID; + } + + public void setArtifactUUID(String artifactUUID) { + this.artifactUUID = artifactUUID; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public String getArtifactname() { + return artifactname; + } + + public void setArtifactname(String artifactname) { + this.artifactname = artifactname; + } + + public String getArtifacttype() { + return artifacttype; + } + + public void setArtifacttype(String artifacttype) { + this.artifacttype = artifacttype; + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/environmentLocal b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/environmentLocal new file mode 100644 index 0000000000..ea93ddfe85 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/datatypes/environmentLocal @@ -0,0 +1,10 @@ +//URL designer +urlDesigner=http://172.20.43.136:8080/sdc1/proxy-designer1#/dashboard +//URL tester +urlTester=http://172.20.43.136:8080/sdc1/proxy-tester1 +//URL Vagrant +urlDesignerVagrant=http://localhost:8181/sdc1/proxy-designer1#/dashboard +//UrlStaging +UrlStaging=https://www.e-access.att.com/sdcpstage/sdc1/portal#/dashboard +//UrlAdmin +UrlAdmin=http://172.20.43.136:8080/sdc1/proxy-admin1#/adminDashboard
\ No newline at end of file diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/GeneralUiRuntimeException.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/GeneralUiRuntimeException.java new file mode 100644 index 0000000000..629421e35e --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/GeneralUiRuntimeException.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.exception; + +@SuppressWarnings("serial") +public class GeneralUiRuntimeException extends RuntimeException { + + public GeneralUiRuntimeException(final String s, final Throwable throwable) { + super(s, throwable); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/HomePageRuntimeException.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/HomePageRuntimeException.java new file mode 100644 index 0000000000..59aa7c0e10 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/HomePageRuntimeException.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.exception; + +@SuppressWarnings("serial") +public class HomePageRuntimeException extends RuntimeException { + + public HomePageRuntimeException(final String s, final Throwable throwable) { + super(s, throwable); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/PropertiesAssignmentPageException.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/PropertiesAssignmentPageException.java new file mode 100644 index 0000000000..4e9b10ed23 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/PropertiesAssignmentPageException.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.exception; + +@SuppressWarnings("serial") +public class PropertiesAssignmentPageException extends Exception { + + public PropertiesAssignmentPageException(final String s, final Throwable throwable) { + super(s, throwable); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/WebDriverThreadRuntimeException.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/WebDriverThreadRuntimeException.java new file mode 100644 index 0000000000..90979edb22 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/exception/WebDriverThreadRuntimeException.java @@ -0,0 +1,29 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.exception; + +@SuppressWarnings("serial") +public class WebDriverThreadRuntimeException extends RuntimeException { + + public WebDriverThreadRuntimeException(final String s, final Throwable throwable) { + super(s, throwable); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/CreatePath.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/CreatePath.java new file mode 100644 index 0000000000..eae7807c9f --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/CreatePath.java @@ -0,0 +1,299 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import org.onap.sdc.backend.ci.tests.datatypes.enums.CircleSize; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.GovernorOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + + +public class CreatePath extends SetupCDTest { + + protected static String filePath = FileHandling.getFilePath("ComplexService"); + private static String fullCompositionFile = "fullComposition.zip"; + private static String fullCompositionFile2 = "fullCompositionNew.zip"; + private static String HSSFile = "HSS.zip"; + private static String VMMEFile = "VMME.zip"; + private static String makeDistributionValue; + + @Parameters({"makeDistribution"}) + @BeforeMethod + public void beforeTestReadParams(@Optional("true") String makeDistributionReadValue) { + makeDistributionValue = makeDistributionReadValue; + } + + //------------------------------------------Tests----------------------------------------------------- + + + // Test#1 Jira issue 5610 + @Test + public void AssertPathButtons() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + getToPathFlow(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + PathUtilities.createService(getUser()); + PathUtilities.openCreatePath(); + PathValidations.AssertCreatePath(); + PathValidations.AssertExtendPath(); + } + + // Test#2 Jira issue 5441 + @Test + public void CreatePathTestSanity() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + Pair<String, ServiceReqDetails> pair = getToPathFlow(resourceReqDetails, filePath, fullCompositionFile); + String vspName = pair.left; + String serviceName = pair.right.getName(); + String pathName = "Test1"; + PathUtilities.createPath(pathName, vspName); + PathValidations.validateServicePath(serviceName, pathName); + } + + // Test#3 Jira issue 5611 + @Test + public void CreatePathCheckIO() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + String serviceName = PathUtilities.createService(getUser()).getName(); + String pathName = PathUtilities.createPath("Test3", vspName); + + // @@ check in @@ + ResourceGeneralPage.clickCheckinButton(serviceName); + GeneralUIUtils.findComponentAndClick(serviceName); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + PathValidations.AssertCreatedPathExistInCompositionPage(pathName); + + // @@ check out @@ + ResourceGeneralPage.clickCheckoutButton(); + PathValidations.AssertCreatedPathExistInCompositionPage(pathName); + } + + // Test#4 Jira issue 5441 + @Test + public void CreateMultiplePaths() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + Pair<String, ServiceReqDetails> pair = getToPathFlow(resourceReqDetails, filePath, HSSFile); + String vspName = pair.left; + PathUtilities.createPath("Test4_path1", vspName); + PathUtilities.createPath("Test4_path2", vspName); + PathValidations.createPathNumOfRows(7); + PathValidations.createPathNumOfRows(6); + SetupCDTest.getExtendTest().log(Status.INFO, "multiple paths have been created"); + } + + // Test#5 Jira issue 5506 + @Test + public void CreatePathWithComplex() throws Exception { + List<String> vnfFiles = new ArrayList<>(); + vnfFiles.add(HSSFile); + vnfFiles.add(VMMEFile); + Pair<String, String> complex = CreatePathComplexServiceFlow(filePath, vnfFiles); + String serviceName = complex.left; + String pathName = complex.right; + PathValidations.validateServicePath(serviceName, pathName); + SetupCDTest.getExtendTest().log(Status.INFO, "path with complex service has been created"); + } + + // Test#6 Jira issue 5506 + @Test + public void CreateExtendedPathWithComplex() throws Exception { + List<String> vnfFiles = new ArrayList<>(); + vnfFiles.add(fullCompositionFile); + vnfFiles.add(fullCompositionFile2); + String[] services = getToComplexService(filePath, vnfFiles); + PathValidations.validateComplexExtendedPath(services); + SetupCDTest.getExtendTest().log(Status.INFO, "path with complex service has been created"); + } + + // Test#7 Jira issue 5441 + @Test + public void CreatePathExtendedTest() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + runCreateExtendedPathFlow(resourceReqDetails, filePath, fullCompositionFile); + } + + //////////////////////////////////////////////////////////////////////////////////////// + // flow methods // + //////////////////////////////////////////////////////////////////////////////////////// + + // workflow leading to path + public String onboardAndCertify(ResourceReqDetails resourceReqDetails, String filePath, String vnfFile) throws Exception { + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser()); + String vspName = vendorSoftwareProductObject.getName(); + + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFile, "The topology template for " + vnfFile + " is as follows : "); + + DeploymentArtifactPage.clickSubmitForTestingButton(vspName); + SetupCDTest.getExtendTest().log(Status.INFO, "relogin as TESTER"); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + return vspName; + } + + public List<String> onboardAndCertifyMultipleVFs(String filePath, List<String> vnfFiles) throws Exception { + List<String> VFNames = new ArrayList<>(); + for (int i = 0; i < vnfFiles.size(); i++) { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFiles.get(i), getUser()); + VFNames.add(i, vendorSoftwareProductObject.getName()); + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFiles.get(i), "The topology template for " + vnfFiles.get(i) + " is as follows : "); + DeploymentArtifactPage.clickSubmitForTestingButton(VFNames.get(i)); + } + SetupCDTest.getExtendTest().log(Status.INFO, "relogin as TESTER"); + reloginWithNewRole(UserRoleEnum.TESTER); + for (String VFName : VFNames) { + GeneralUIUtils.findComponentAndClick(VFName); + TesterOperationPage.certifyComponent(VFName); + } + return VFNames; + } + + public Pair<String, ServiceReqDetails> getToPathFlow(ResourceReqDetails resourceReqDetails, String filepath, String vnfFile) throws Exception { + String vspName = onboardAndCertify(resourceReqDetails, filepath, vnfFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails serviceMetadata = PathUtilities.createService(getUser()); + return new Pair<>(vspName, serviceMetadata); + } + + public String[] getToComplexService(String filepath, List<String> vnfFiles) throws Exception { + // create & certify 2 VF + List<String> VFNames = onboardAndCertifyMultipleVFs(filepath, vnfFiles); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails serviceMetadata1 = PathUtilities.createService(getUser()); + + // create path 1 + PathUtilities.createPath("newPath", VFNames.get(0)); + PathUtilities.submitForTesting(); + GeneralUIUtils.ultimateWait(); + ServiceReqDetails serviceMetadata2 = PathUtilities.createService(getUser()); + + // create path 2 + PathUtilities.createPath("newPath2", VFNames.get(1)); + PathUtilities.submitForTesting(); + + //tester + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName()); + TesterOperationPage.certifyComponent(serviceMetadata1.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName()); + TesterOperationPage.certifyComponent(serviceMetadata2.getName()); + + //governor + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName()); + GovernorOperationPage.approveService(serviceMetadata1.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName()); + GovernorOperationPage.approveService(serviceMetadata2.getName()); + + //create service for complex service + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails serviceMetadata3 = PathUtilities.createService(getUser()); + return new String[]{serviceMetadata1.getName(), serviceMetadata2.getName(), serviceMetadata3.getName()}; + } + + public Pair<String, String> CreatePathComplexServiceFlow(String filepath, List<String> vnfFiles) throws Exception { + String[] servicesName = getToComplexService(filepath, vnfFiles); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(servicesName[0]); + CanvasElement service1 = canvasManager.createElementOnCanvas(servicesName[0]); + CompositionPage.searchForElement(servicesName[1]); + CanvasElement service2 = canvasManager.createElementOnCanvas(servicesName[1]); + canvasManager.linkElements(service1, CircleSize.SERVICE, service2, CircleSize.SERVICE); + + // create path + String pathName = "name1"; + PathUtilities.openCreatePath(); + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()).click(); + return new Pair<>(servicesName[2], pathName); + } + + public void runCreateExtendedPathFlow(ResourceReqDetails resourceReqDetails, String filepath, String vnfFile) throws Exception { + Pair<String, ServiceReqDetails> pair = getToPathFlow(resourceReqDetails, filepath, vnfFile); + String vspName = pair.left; + PathUtilities.linkVFs(vspName, 4); + + //create path + PathUtilities.openCreatePath(); + String pathName = "name1"; + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + int numOfLines = 3; + PathValidations.extendPath(numOfLines); + + //delete line + PathUtilities.deleteLines(1, numOfLines); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + ExtentTestActions.log(Status.INFO, "path has been created"); + + // check path is on the list + PathUtilities.openPathList(); + String PathListName1 = GeneralUIUtils.findByText(pathName).getText(); + String newPathName = "name2"; + PathUtilities.editPathName(pathName, newPathName); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.PATH_MENU_BUTTON.getValue() + "']/parent::*").get(0).click(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue()); + String PathListName2 = GeneralUIUtils.findByText(newPathName).getText(); + PathValidations.AssertNameChangeFromPathList(PathListName1, PathListName2); + + // delete path and validate + PathValidations.ValidateAndDeletePathFromPathList(newPathName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "Path has been created"); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/ElementsChanges.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/ElementsChanges.java new file mode 100644 index 0000000000..ce0053c74d --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/ElementsChanges.java @@ -0,0 +1,735 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import org.apache.http.HttpStatus; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GovernorOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotSame; + + +public class +ElementsChanges extends SetupCDTest { + + private static final int NUMBER_OF_LINKS = 3; + protected static String filePath = FileHandling.getFilePath("ComplexService"); + private static String fullCompositionFile = "fullComposition.zip"; + private static String test = "test.zip"; + private static String fullCompositionFile2 = "test.zip"; + private static String HSSFile = "HSS.zip"; + private static String VMMEFile = "VMME.zip"; + private static String WithPort = "withPort.zip"; + private static String withoutPort = "withoutPort.zip"; + private static String makeDistributionValue; + + @Parameters({"makeDistribution"}) + @BeforeMethod + public void beforeTestReadParams(@Optional("true") String makeDistributionReadValue) { + makeDistributionValue = makeDistributionReadValue; + } + + //------------------------------------------Tests----------------------------------------------------- + + // Test#1 Jira issue 6324 + @Test + public void DeleteComponent() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails serviceMetadata = PathUtilities.createService(getUser()); + List<CanvasElement> VFs = PathUtilities.linkVFs(vspName, NUMBER_OF_LINKS); + String pathName = PathUtilities.createPathWithoutLink("DeleteComponent", vspName); + PathUtilities.deleteComponents(VFs); + PathValidations.validatePathListIsEmpty(); + certifyServiceAsTester(serviceMetadata); + + } + + // Test#2 Jira issue 6325 + @Test + public void DeleteServiceComponent() throws Exception { + ServiceReqDetails serviceMetadata = getToComplexService(filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails complexService = PathUtilities.createService(getUser()); + List<CanvasElement> services = createComplexPath(serviceMetadata.getName()); + PathUtilities.deleteComponents(services); + PathValidations.validatePathListIsEmpty(); + certifyServiceAsTester(complexService); + } + + // Test#3 Jira issue 6364 + @Test + public void ManualUpdateVF() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails serviceMetadata = PathUtilities.createService(getUser()); + PathUtilities.createPath("ManualUpdateVF", vspName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.HOME_FROM_COMPOSITION.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.MainMenuButtons.ONBOARD_BUTTON.getValue()); + /// GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.ONBOARD_CATALOG.getValue()); + ResourceUIUtils.clickOnElementByText(vspName, null); + ResourceUIUtils.clickOnElementByText("Create New Version", null); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ComplexServiceAmdocs.NEW_VSP_VERSION_DESCRIPTION.getValue()).sendKeys("new vsap version for service path"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.SUBMIT_NEW_VSP_VERSION_DESCRIPTION.getValue()); + + // VendorSoftwareProductObject v = new VendorSoftwareProductObject(); + //VendorSoftwareProductRestUtils.uploadHeatPackage(filePath,fullCompositionFile,v,getUser()); +//upload new heat +commit submit + //go to home + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.MainMenuButtons.ONBOARD_BUTTON.getValue()); + + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + // CanvasManager.getCanvasManager().clickOnCanvaElement(vf); + //update version + //validate path still exist + certifyServiceAsTester(serviceMetadata); + } + + @Test + public void UpdateComponent() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, VMMEFile); + + } + + @Test + public void UpdateComponentWithouForwarder() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vsp_v2_description = "change description for version 2"; + VendorSoftwareProductObject vendorSoftwareProductObject = getToPathServiceVersions(resourceReqDetails, filePath, WithPort, vsp_v2_description, withoutPort, getUser()); + + // create service + ServiceReqDetails service = PathUtilities.createService(getUser()); + + // create path + String vspName = vendorSoftwareProductObject.getName(); + String pathName = "path1"; + List<CanvasElement> VFs = PathUtilities.linkVFs(vspName, 2); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + for (CanvasElement element : VFs) { + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + } + PathUtilities.openCreatePath(); + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + PathValidations.extendPath(NUMBER_OF_LINKS); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + + ///////////////// + // test case // + ///////////////// + + // validate version change has no effect + for (CanvasElement element : VFs) { + RestResponse ServiceForwardingPathsResponse = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + // change to version with different capabiliteis + CompositionPage.changeComponentVersion(canvasManager, element, "3.0", false); + // click on warning message + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths changed + RestResponse ServiceForwardingPathsResponse2 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertNotSame( + "response message failed expectation, expectation is to change", + ServiceForwardingPathsResponse.getResponse(), + ServiceForwardingPathsResponse2.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths hasn't changed + RestResponse ServiceForwardingPathsResponse3 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertEquals( + "response message failed expectation, expectation is not to change", + ServiceForwardingPathsResponse2.getResponse(), + ServiceForwardingPathsResponse3.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + } + + /////////////////////// + // post requisites // + /////////////////////// + + // finish flow + certifyServiceAsTester(service); + } + + //TODO run and debug +// Test#3 Jira issue - 6230 + @Test + public void ValidatePathServiceVersions() throws Exception { + + ////////////////////// + // pre requisites // + ////////////////////// + + // start flow + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vsp_v2_description = "change description for version 2"; + VendorSoftwareProductObject vendorSoftwareProductObject = getToPathServiceVersions(resourceReqDetails, filePath, HSSFile, vsp_v2_description, fullCompositionFile, getUser()); + + // create service + ServiceReqDetails service = PathUtilities.createService(getUser()); + + // create path + String vspName = vendorSoftwareProductObject.getName(); + String pathName = "path1"; + List<CanvasElement> VFs = PathUtilities.linkVFs(vspName, 2); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + for (CanvasElement element : VFs) { + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + } + PathUtilities.openCreatePath(); + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + PathValidations.extendPath(NUMBER_OF_LINKS); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + + ///////////////// + // test case // + ///////////////// + + // validate version change has no effect + for (CanvasElement element : VFs) { + RestResponse ServiceForwardingPathsResponse = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + + CompositionPage.changeComponentVersion(canvasManager, element, "2.0", false); + // validate paths hasn't changed + RestResponse ServiceForwardingPathsResponse2 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertEquals( + "response message failed expectation, expectation is not to change", + ServiceForwardingPathsResponse.getResponse(), + ServiceForwardingPathsResponse2.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + // validate paths hasn't changed + RestResponse ServiceForwardingPathsResponse3 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertEquals( + "response message failed expectation, expectation is not to change", + ServiceForwardingPathsResponse.getResponse(), + ServiceForwardingPathsResponse3.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + } + + /////////////////////// + // post requisites // + /////////////////////// + + // finish flow + certifyServiceAsTester(service); + } + + //TODO run and debug +// Test#3 Jira issue - 6189 + @Test + public void ValidatePathServiceVersionsDifferentCapabilities() throws Exception { + + ////////////////////// + // pre requisites // + ////////////////////// + + // start flow + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vsp_v2_description = "change description for version 2"; + VendorSoftwareProductObject vendorSoftwareProductObject = getToPathServiceVersions(resourceReqDetails, filePath, HSSFile, vsp_v2_description, fullCompositionFile, getUser()); + + // create service + ServiceReqDetails service = PathUtilities.createService(getUser()); + + // create path + String vspName = vendorSoftwareProductObject.getName(); + String pathName = "path1"; + List<CanvasElement> VFs = PathUtilities.linkVFs(vspName, 2); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + for (CanvasElement element : VFs) { + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + } + PathUtilities.openCreatePath(); + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + PathValidations.extendPath(NUMBER_OF_LINKS); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + + ///////////////// + // test case // + ///////////////// + + // validate version change has no effect + for (CanvasElement element : VFs) { + RestResponse ServiceForwardingPathsResponse = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + // change to version with different capabiliteis + CompositionPage.changeComponentVersion(canvasManager, element, "3.0", false); + // click on warning message + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths changed + RestResponse ServiceForwardingPathsResponse2 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertNotSame( + "response message failed expectation, expectation is to change", + ServiceForwardingPathsResponse.getResponse(), + ServiceForwardingPathsResponse2.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths hasn't changed + RestResponse ServiceForwardingPathsResponse3 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertEquals( + "response message failed expectation, expectation is not to change", + ServiceForwardingPathsResponse2.getResponse(), + ServiceForwardingPathsResponse3.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + } + + /////////////////////// + // post requisites // + /////////////////////// + + // finish flow + certifyServiceAsTester(service); + } + + //TODO run and debug +// Test#3 Jira issue - 6231 + @Test + public void ValidatePathServiceVersionsnegative() throws Exception { + + ////////////////////// + // pre requisites // + ////////////////////// + + // start flow + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vsp_v2_description = "change description for version 2"; + VendorSoftwareProductObject vendorSoftwareProductObject = getToPathServiceVersions(resourceReqDetails, filePath, HSSFile, vsp_v2_description, fullCompositionFile, getUser()); + + // create service + ServiceReqDetails service = PathUtilities.createService(getUser()); + + // create path + String vspName = vendorSoftwareProductObject.getName(); + String pathName = "path1"; + List<CanvasElement> VFs = PathUtilities.linkVFs(vspName, 2); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + for (CanvasElement element : VFs) { + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + } + PathUtilities.openCreatePath(); + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + PathValidations.extendPath(NUMBER_OF_LINKS); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + + ///////////////// + // test case // + ///////////////// + + // validate version change has no effect + for (CanvasElement element : VFs) { + RestResponse ServiceForwardingPathsResponse = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + // change to version with different capabiliteis + CompositionPage.changeComponentVersion(canvasManager, element, "3.0", false); + // click on warning message to cancel + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ModalItems.CANCEL.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths changed + RestResponse ServiceForwardingPathsResponse2 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertEquals( + "response message failed expectation, expectation is not to change", + ServiceForwardingPathsResponse.getResponse(), + ServiceForwardingPathsResponse2.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + + CompositionPage.changeComponentVersion(canvasManager, element, "3.0", true); + // click on warning message + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths hasn't changed + RestResponse ServiceForwardingPathsResponse3 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertNotSame( + "response message failed expectation, expectation is to change", + ServiceForwardingPathsResponse2.getResponse(), + ServiceForwardingPathsResponse3.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + } + + /////////////////////// + // post requisites // + /////////////////////// + + // finish flow + certifyServiceAsTester(service); + } + + //TODO finish +// Test#3 Jira issue - 6189 + @Test + public void ValidatePathServiceVersionsDifferentCapabilitiesInComplexService() throws Exception { + + ////////////////////// + // pre requisites // + ////////////////////// + + // start flow + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vsp_v2_description = "change description for version 2"; + VendorSoftwareProductObject vendorSoftwareProductObject = getToPathServiceVersions(resourceReqDetails, filePath, HSSFile, vsp_v2_description, fullCompositionFile, getUser()); + + // create service + ServiceReqDetails service = PathUtilities.createService(getUser()); + + // create path + String vspName = vendorSoftwareProductObject.getName(); + String pathName = "path1"; + List<CanvasElement> VFs = PathUtilities.linkVFs(vspName, 2); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + for (CanvasElement element : VFs) { + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + } + PathUtilities.openCreatePath(); + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + PathValidations.extendPath(NUMBER_OF_LINKS); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + + // certify Service + certifyServiceAsTester(service); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + + // create new version + GeneralUIUtils.findComponentAndClick(service.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + canvasManager = CanvasManager.getCanvasManager(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.LifeCyleChangeButtons.CHECKOUT.getValue()); + + ///////////////// + // test case // + ///////////////// + + // validate version change has no effect + for (CanvasElement element : VFs) { + RestResponse ServiceForwardingPathsResponse = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + // change to version with different capabilities + CompositionPage.changeComponentVersion(canvasManager, element, "3.0", false); + // click on warning message + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths changed + RestResponse ServiceForwardingPathsResponse2 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertNotSame( + "response message failed expectation, expectation is to change", + ServiceForwardingPathsResponse.getResponse(), + ServiceForwardingPathsResponse2.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + + CompositionPage.changeComponentVersion(canvasManager, element, "1.0", false); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']").get(0).click(); + GeneralUIUtils.ultimateWait(); + // validate paths hasn't changed + RestResponse ServiceForwardingPathsResponse3 = PathUtilities.getServiceForwardingPathsAPI(service.getName()); + assertEquals( + "response message failed expectation, expectation is not to change", + ServiceForwardingPathsResponse2.getResponse(), + ServiceForwardingPathsResponse3.getResponse()); + // validate there are no error messages + PathValidations.ValidateThereIsNoErrorMessage(); + } + + /////////////////////// + // post requisites // + /////////////////////// + + // finish flow + certifyServiceAsTester(service); + } + + @Test + public void ComplexServiceSanity() throws Exception { + // create & certify 2 VFs + List<String> vnfFiles = new ArrayList<>(); + vnfFiles.add(HSSFile); + vnfFiles.add(fullCompositionFile); + List<String> VFNames = onboardAndCertifyMultipleVFs(filePath, vnfFiles); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + // create service 1 + ServiceReqDetails serviceMetadata1 = PathUtilities.createService(getUser()); + + // create path 1 + String path1 = "newPath"; + PathUtilities.createPath(path1, VFNames.get(0)); + PathUtilities.submitForTesting(); + GeneralUIUtils.ultimateWait(); + + // create service 2 + ServiceReqDetails serviceMetadata2 = PathUtilities.createService(getUser()); + + // create path 2 + String path2 = "newPath2"; + PathUtilities.createPath(path2, VFNames.get(1)); + PathUtilities.submitForTesting(); + + // tester + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName()); + TesterOperationPage.certifyComponent(serviceMetadata1.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName()); + TesterOperationPage.certifyComponent(serviceMetadata2.getName()); + + // governor + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName()); + GovernorOperationPage.approveService(serviceMetadata1.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata2.getName()); + GovernorOperationPage.approveService(serviceMetadata2.getName()); + + // create service for complex service + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails serviceMetadata3 = PathUtilities.createService(getUser()); + + // validate complex's path + String[] services = {serviceMetadata1.getName(), serviceMetadata2.getName(), serviceMetadata3.getName()}; + PathValidations.validateComplexExtendedPath(services); + + // validate certification + certifyServiceAsTester(serviceMetadata3); + } + + //////////////////////////////////////////////////////////////////////////////////////// + // flow methods // + //////////////////////////////////////////////////////////////////////////////////////// + + // workflow leading to path + public String onboardAndCertify(ResourceReqDetails resourceReqDetails, String filePath, String vnfFile) throws Exception { + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser()); + String vspName = vendorSoftwareProductObject.getName(); + + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFile, "The topology template for " + vnfFile + " is as follows : "); + + DeploymentArtifactPage.clickSubmitForTestingButton(vspName); + SetupCDTest.getExtendTest().log(Status.INFO, "relogin as TESTER"); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + return vspName; + } + + public List<String> onboardAndCertifyMultipleVFs(String filePath, List<String> vnfFiles) throws Exception { + List<String> VFNames = new ArrayList<>(); + for (int i = 0; i < vnfFiles.size(); i++) { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFiles.get(i), getUser()); + VFNames.add(i, vendorSoftwareProductObject.getName()); + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFiles.get(i), "The topology template for " + vnfFiles.get(i) + " is as follows : "); + DeploymentArtifactPage.clickSubmitForTestingButton(VFNames.get(i)); + } + SetupCDTest.getExtendTest().log(Status.INFO, "relogin as TESTER"); + reloginWithNewRole(UserRoleEnum.TESTER); + for (String VFName : VFNames) { + GeneralUIUtils.findComponentAndClick(VFName); + TesterOperationPage.certifyComponent(VFName); + } + return VFNames; + } + + public static List<CanvasElement> createComplexPath(String service) throws Exception { + List<CanvasElement> services = PathUtilities.linkServices(service, service, NUMBER_OF_LINKS); + PathUtilities.createPathWithoutLink("name1", service); + PathUtilities.createPathWithoutLink("name2", service); + return services; + } + + public ServiceReqDetails getToComplexService(String filepath, String vnfFile) throws Exception { + // create & certify VF + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filepath, vnfFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ServiceReqDetails serviceMetadata1 = PathUtilities.createService(getUser()); + + // create path + PathUtilities.createPath("newPath", vspName); + PathUtilities.submitForTesting(); + GeneralUIUtils.ultimateWait(); + + //tester + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName()); + TesterOperationPage.certifyComponent(serviceMetadata1.getName()); + + //governor + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata1.getName()); + GovernorOperationPage.approveService(serviceMetadata1.getName()); + return serviceMetadata1; + } + + public VendorSoftwareProductObject getToPathServiceVersions(ResourceReqDetails resourceReqDetails, String filepath, String vnfFileV1, String descriptionV2, String vnfFileV3, User user) throws Exception { + + //////////////////////////////////// + // VF v1 // + //////////////////////////////////// + + VendorSoftwareProductObject vendorSoftwareProduct = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFileV1, getUser()); + String vspName = vendorSoftwareProduct.getName(); + + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFileV1, "The topology template for " + vnfFileV1 + " is as follows : "); + DeploymentArtifactPage.clickSubmitForTestingButton(vspName); + SetupCDTest.getExtendTest().log(Status.INFO, "relogin as TESTER"); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + //////////////////////////////////// + // VF v2 // + //////////////////////////////////// + + // vsp create new version + Pair<RestResponse, OnboardItemObject> newItemVersion = PathUtilities.createNewItemVersion( + vendorSoftwareProduct.getVspId(), + vendorSoftwareProduct.getComponentId(), + "version with different description", user); + assertEquals("did not succeed to create new item version", HttpStatus.SC_OK, newItemVersion.left.getErrorCode().intValue()); + vendorSoftwareProduct.setVersion(newItemVersion.right.getItemId()); + vendorSoftwareProduct.setComponentId(newItemVersion.right.getItemId()); + + // update vsp description + vendorSoftwareProduct.setDescription(descriptionV2); + RestResponse restResponse = PathUtilities.updateVendorSoftwareProduct(vendorSoftwareProduct, user); + assertEquals("did not succeed to update vsp", HttpStatus.SC_OK, restResponse.getErrorCode().intValue()); + + // commit & submit vsp + VendorSoftwareProductRestUtils.prepareVspForUse(user, vendorSoftwareProduct, false); + + // update VF + HomePage.showVspRepository(); + PathUtilities.updateVF(vspName, vendorSoftwareProduct); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.UPDATE_VF.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.SUBMIT_FOR_TESTING_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + + // certify VF + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + //////////////////////////////////// + // VF v3 // + //////////////////////////////////// + + // create new version + newItemVersion = PathUtilities.createNewItemVersion( + vendorSoftwareProduct.getVspId(), + vendorSoftwareProduct.getVersion(), + "version with different heat", user); + assertEquals("did not succeed to create new item version", HttpStatus.SC_OK, newItemVersion.left.getErrorCode().intValue()); + vendorSoftwareProduct.setVersion(newItemVersion.right.getItemId()); + vendorSoftwareProduct.setComponentId(newItemVersion.right.getItemId()); + + // upload new heat + RestResponse uploadHeatPackage = VendorSoftwareProductRestUtils.uploadHeatPackage(filepath, vnfFileV3, vendorSoftwareProduct, user); + assertEquals("did not succeed to upload HEAT package", HttpStatus.SC_OK, uploadHeatPackage.getErrorCode().intValue()); + + RestResponse validateUpload = VendorSoftwareProductRestUtils.validateUpload(vendorSoftwareProduct, user); + assertEquals("did not succeed to validate upload process, reason: " + validateUpload.getResponse(), HttpStatus.SC_OK, validateUpload.getErrorCode().intValue()); + + // commit & submit vsp + VendorSoftwareProductRestUtils.prepareVspForUse(user, vendorSoftwareProduct, false); + + // update VF + HomePage.showVspRepository(); + PathUtilities.updateVF(vspName, vendorSoftwareProduct); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.SUBMIT_FOR_TESTING_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + + // certify VF + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + reloginWithNewRole(UserRoleEnum.DESIGNER); + + return vendorSoftwareProduct; + } + + public void certifyServiceAsTester(ServiceReqDetails serviceMetaData) throws Exception { + PathUtilities.submitForTesting(); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetaData.getName()); + TesterOperationPage.certifyComponent(serviceMetaData.getName()); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/OnboardItemObject.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/OnboardItemObject.java new file mode 100644 index 0000000000..5f62f24086 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/OnboardItemObject.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + + +public class OnboardItemObject extends OnboardItemObjectReqDetails { + + private String itemId; + private String name; + private String baseId; + private String status; + + public OnboardItemObject() { + super(); + } + + public OnboardItemObject(String itemId, String name, String baseId, String status) { + this.itemId = itemId; + this.name = name; + this.baseId = baseId; + this.status = status; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + + public String getName() { + return name; + } + + public void setName(String itemId) { + this.name = name; + } + + public String getBaseId() { + return baseId; + } + + public void setBaseId(String baseId) { + this.baseId = baseId; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return "OnboardItemObject{" + + "itemId='" + itemId + '\'' + + ", name='" + name + '\'' + + ", baseId='" + baseId + '\'' + + ", status='" + status + '\'' + + '}'; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/OnboardItemObjectReqDetails.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/OnboardItemObjectReqDetails.java new file mode 100644 index 0000000000..e9379cd59a --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/OnboardItemObjectReqDetails.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + + +public class OnboardItemObjectReqDetails { + + private String creationMethod; + private String description; + + public OnboardItemObjectReqDetails() { + } + + public OnboardItemObjectReqDetails(String creationMethod, String description) { + this.creationMethod = creationMethod; + this.description = description; + } + + public String getCreationMethod() { + return creationMethod; + } + + public void setCreationMethod(String creationMethod) { + this.creationMethod = creationMethod; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String toString() { + return "OnboardItemObjectReqDetails{" + + "creationMethod='" + creationMethod + '\'' + + ", description='" + description + '\'' + + '}'; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathName.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathName.java new file mode 100644 index 0000000000..c889faf0d6 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathName.java @@ -0,0 +1,136 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +public class PathName extends SetupCDTest { + + protected static String filePath = FileHandling.getFilePath("ComplexService"); + private static String fullCompositionFile = "fullComposition.zip"; + private static String fullCompositionFile2 = "fullCompositionNew.zip"; + private static String HSSFile = "HSS.zip"; + private static String VMMEFile = "VMME.zip"; + private static String makeDistributionValue; + + @Parameters({"makeDistribution"}) + @BeforeMethod + public void beforeTestReadParams(@Optional("true") String makeDistributionReadValue) { + makeDistributionValue = makeDistributionReadValue; + } + + //------------------------------------------Tests----------------------------------------------------- + + // Test#8 Jira issue 6168 + @Test + public void ValidateSameNameTest() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + PathUtilities.createService(getUser()); + String firstPathName = PathUtilities.createPath("Oren", vspName); + PathUtilities.createPathWithoutLink(firstPathName, vspName); + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } catch (Exception e) { + throw new Exception("when creating another path with duplicate name, expected error did not appear"); + } + } + + // Test#9 Jira issue 6183 + @Test + public void ValidateEditName() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + PathUtilities.createService(getUser()); + String firstPathName = PathUtilities.createPath("Oren", vspName); + String secondPathName = PathUtilities.createPathWithoutLink("blabla", vspName); + PathValidations.validateEditToExistingName(firstPathName, secondPathName); + } + + // Test#10 Jira issue 6411 + @Test + public void SpacesName() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + PathUtilities.createService(getUser()); + PathUtilities.createPath(" ", vspName); + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } catch (Exception e) { + throw new Exception("service path name cannot be empty or spaces "); + } + } + + // Test#11 Jira issue 6186 + @Test + public void ValidateNameWithSpaces() throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + String vspName = onboardAndCertify(resourceReqDetails, filePath, fullCompositionFile); + reloginWithNewRole(UserRoleEnum.DESIGNER); + PathUtilities.createService(getUser()); + PathValidations.validateNameWithSpaces("New", vspName); + } + + //////////////////////////////////////////////////////////////////////////////////////// + // flow methods // + //////////////////////////////////////////////////////////////////////////////////////// + + // workflow leading to path + public String onboardAndCertify(ResourceReqDetails resourceReqDetails, String filePath, String vnfFile) throws Exception { + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser()); + String vspName = vendorSoftwareProductObject.getName(); + + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFile, "The topology template for " + vnfFile + " is as follows : "); + + DeploymentArtifactPage.clickSubmitForTestingButton(vspName); + SetupCDTest.getExtendTest().log(Status.INFO, "relogin as TESTER"); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vspName); + TesterOperationPage.certifyComponent(vspName); + return vspName; + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +}
\ No newline at end of file diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathUrls.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathUrls.java new file mode 100644 index 0000000000..483b279932 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathUrls.java @@ -0,0 +1,37 @@ +package org.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + +/*- + * ============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========================================================= + */ + +import org.onap.sdc.backend.ci.tests.utils.Utils; + + +public interface PathUrls { + + String SDC_HTTP_METHOD = Utils.getConfigHandleException() == null ? "http" : Utils.getConfigHandleException().getSdcHttpMethod(); + String AMDOCS_HTTP_METHOD = SDC_HTTP_METHOD; + + // onboard + String CREATE_NEW_ITEM_VERSION = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/items/%s/versions/%s/"; + String UPDATE_VENDOR_SOFTWARE_PRODUCT = SDC_HTTP_METHOD + "://%s:%s/onboarding-api/v1.0/vendor-software-products/%s/versions/%s"; + String GET_SERVICE_PATHS = SDC_HTTP_METHOD + "://%s:%s/sdc1/feProxy/rest/v1/catalog/services/%s/filteredDataByParams?include=componentInstancesRelations&include=componentInstances&include=forwardingPaths"; + String SERVICE_PATH_LINK_MAP = SDC_HTTP_METHOD + "://%s:%s/sdc1/rest/v1/catalog/services/%s/linksMap"; + String SERVICE_FORWARDING_PATHS = SDC_HTTP_METHOD + "://%s:%s/sdc1/rest/v1/catalog/services/%s/filteredDataByParams?include=componentInstancesRelations&include=componentInstances&include=forwardingPaths"; +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathUtilities.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathUtilities.java new file mode 100644 index 0000000000..30099645df --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathUtilities.java @@ -0,0 +1,439 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import com.google.gson.Gson; +import org.apache.http.HttpStatus; +import org.onap.sdc.backend.ci.tests.config.Config; +import org.onap.sdc.backend.ci.tests.datatypes.http.HttpHeaderEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.HttpRequest; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser; +import org.onap.sdc.backend.ci.tests.utils.rest.ServiceRestUtils; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.AssertJUnit.assertEquals; + + +public class PathUtilities { + + private static final int WAITING_FOR_LOADRE_TIME_OUT = 60 * 10; + private static final int NUMBER_OF_LINKS = 3; + + static void openPathList() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_MENU_BUTTON.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue()); + } + + public static ServiceReqDetails createService(User user) throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + GeneralUIUtils.ultimateWait(); + return serviceMetadata; + } + + public static List<CanvasElement> linkVFs(String vspName, int linksNum) throws Exception { + CompositionPage.searchForElement(vspName); + GeneralUIUtils.ultimateWait(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + GeneralUIUtils.ultimateWait(); + List<CanvasElement> VFs = new ArrayList<CanvasElement>(); + VFs.add(canvasManager.createElementOnCanvas(vspName)); + for (int i = 1; i < linksNum; i++) { + VFs.add(canvasManager.createElementOnCanvas(vspName)); + GeneralUIUtils.ultimateWait(); +// for(int a=0; a<3; a++) +// try { +// canvasManager.linkElements(VFs.get(i), CircleSize.VF, VFs.get(i - 1), CircleSize.VF); +// break; +// } catch (Exception ignore) {} + SetupCDTest.getExtendTest().log(Status.INFO, "link VFs"); + GeneralUIUtils.ultimateWait(); + } + return VFs; + } + + public static List<CanvasElement> linkServices(String service1, String service2, int linksNum) throws Exception { + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + List<CanvasElement> VFs = new ArrayList<CanvasElement>(); + + // get first service + CompositionPage.searchForElement(service1); + VFs.add(canvasManager.createElementOnCanvas(service1)); + + String service = service2; + for (int i = 1; i < linksNum; i++) { + CompositionPage.searchForElement(service); + VFs.add(canvasManager.createElementOnCanvas(service)); + GeneralUIUtils.ultimateWait(); +// for(int a=0; a<3; a++) +// try { +// canvasManager.linkElements(VFs.get(i), CircleSize.SERVICE, VFs.get(i-1), CircleSize.SERVICE); +// break; +// } catch (Exception ignore) {} + SetupCDTest.getExtendTest().log(Status.INFO, "link services"); + GeneralUIUtils.ultimateWait(); + + // change service to link + if (service.equals(service2)) { + service = service1; + } else { + service = service2; + } + } + return VFs; + } + + public static void openCreatePath() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_MENU_BUTTON.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_PATH_MENU_BUTTON.getValue()); + } + + public static void sendValue(String DataTestId, String value) throws Exception { + GeneralUIUtils.getWebElementByTestID(DataTestId).sendKeys(value); + GeneralUIUtils.ultimateWait(); + } + + public static void insertValues(String pathName, String pathProtocol, String pathPortNumbers) throws Exception { + sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_NAME.getValue(), pathName); + sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_PROTOCOL.getValue(), pathProtocol); + sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_PORT_NUMBER.getValue(), pathPortNumbers); + GeneralUIUtils.ultimateWait(); + } + + public static void selectFirstLineParam() throws Exception { + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_SOURCE.getValue() + "']//option").get(0).click(); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_SOURCE_CP.getValue() + "']//option").get(0).click(); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_TARGET.getValue() + "']//option").get(0).click(); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_TARGET_CP.getValue() + "']//option").get(0).click(); + } + + public static void editPathName(String pathName, String newName) throws Exception { + GeneralUIUtils.findElementsByXpath("//*[text()='" + pathName + "']/parent::*//span").get(0).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ComplexServiceAmdocs.PATH_NAME.getValue()).clear(); + sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_NAME.getValue(), newName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.SAVE.getValue()); + } + + public static void editPathProtocol(String pathName, String newProtocol) throws Exception { + GeneralUIUtils.findElementsByXpath("//*[text()='" + pathName + "']/parent::*//span").get(0).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ComplexServiceAmdocs.PATH_PROTOCOL.getValue()).clear(); + sendValue(DataTestIdEnum.ComplexServiceAmdocs.PATH_PROTOCOL.getValue(), newProtocol); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.SAVE.getValue()); + } + + public static int deleteLines(int numOfLinesToDelete, int numOfLines) throws Exception { + for (int i = 0; i < numOfLinesToDelete; i++) { + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.REMOVE_LINK.getValue() + "']//span").get(0).click(); + numOfLines--; + } + if (GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_TARGET_CP + "']//option").size() > (numOfLines + 1)) { + throw new Exception("Path element was not deleted"); + } + GeneralUIUtils.ultimateWait(); + return numOfLines; + } + + public static String createPath(String pathName, String vspName) throws Exception { + linkVFs(vspName, NUMBER_OF_LINKS); + openCreatePath(); + insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + selectFirstLineParam(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "path" + pathName + " has been created"); + return pathName; + } + + public static void deleteComponents(List<CanvasElement> elements) throws Exception { + for (CanvasElement element : elements) { + CanvasManager.getCanvasManager().clickOnCanvaElement(element); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.DELETE_COMPONENT.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } + } + + public static void updateVF(String vspName, VendorSoftwareProductObject vendorSoftwareProduct) throws Exception { + boolean vspFound = HomePage.searchForVSP(vspName); + if (vspFound) { + final List<WebElement> elementsFromTable = GeneralPageElements.getElementsFromTable(); + elementsFromTable.get(1).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); + + OnboardingUiUtils.doCheckOut(); + + //Metadata verification + VfVerificator.verifyOnboardedVnfMetadata(vspName, vendorSoftwareProduct); + + 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); + } + } + + public static void waitUntilVnfCreated() { + GeneralUIUtils.clickOnElementByTestIdWithoutWait(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(WAITING_FOR_LOADRE_TIME_OUT); + GeneralUIUtils.waitForAngular(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + + public static void deleteComponent(CanvasElement element) throws Exception { + CanvasManager.getCanvasManager().clickOnCanvaElement(element); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.DELETE_COMPONENT.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } + + public static void submitForTesting() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.SUBMIT_FOR_TESTING.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ComplexServiceAmdocs.CHANGE_LIFE_CYCLE_MESSAGE.getValue()).sendKeys("new service to certify"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } + + public static String createPathWithoutLink(String pathName, String vspName) throws Exception { + openCreatePath(); + insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + selectFirstLineParam(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "path" + pathName + " has been created"); + return pathName; + } + + // rest apis + private static String getServiceUUIDfromCompositionURL() throws Exception { + String url = SetupCDTest.getDriver().getCurrentUrl(); + String[] result = url.split("/"); + for (int i = 0; i < result.length; i++) { + if (result[i].equals("workspace")) { + return result[i + 1]; + } + } + throw new Exception("service uuid not found in the url"); + } + + private static Map<String, String> prepareHeadersMap(String userId) { + Map<String, String> headersMap = new HashMap<String, String>(); + 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<RestResponse, ServiceReqDetails> getServiceIDByNameAndVersion(String serviceName, String version) throws Exception { + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + RestResponse restResponse = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, serviceName, version); + ServiceReqDetails service = new ServiceReqDetails(); + service.setName(serviceName); + service.setUniqueId(ResponseParser.getUniqueIdFromResponse(restResponse)); + service.setVersion(version); + + return new Pair<>(restResponse, service); + } + + public static RestResponse createServiceAPI(User sdncUserDetails, ServiceReqDetails serviceDetails) throws Exception { + String serviceBaseVersion = "0.1"; + RestResponse restResponse = ServiceRestUtils.createService(serviceDetails, sdncUserDetails); + assertEquals("Check API response code for CreateServiceAPI call", HttpStatus.SC_CREATED, restResponse.getErrorCode().intValue()); + return restResponse; + } + + public static RestResponse getServiceAPI(User sdncUserDetails, ServiceReqDetails serviceDetails) throws Exception { + String serviceBaseVersion = "0.1"; + // choose user + // User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // create serviceDetails + // ServiceReqDetails serviceDetails = ElementFactory.getDefaultService(); + + // get service + RestResponse restResponse = ServiceRestUtils.getServiceByNameAndVersion(sdncUserDetails, serviceDetails.getName(), + serviceBaseVersion); + assertEquals("Check API response code for GetServiceAPI call", HttpStatus.SC_OK, restResponse.getErrorCode().intValue()); + + Service service = ResponseParser.convertServiceResponseToJavaObject(restResponse.getResponse()); + String uniqueId = service.getUniqueId(); + serviceDetails.setUniqueId(uniqueId); + // ServiceValidationUtils.validateServiceResponseMetaData(serviceDetails, service, sdncUserDetails, (LifecycleStateEnum) null); + return restResponse; + } + + public static RestResponse getServiceForwardingPathsAPI(String serviceName) throws Exception { + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + // get service + Pair<RestResponse, ServiceReqDetails> servicePaths = getServiceIDByNameAndVersion(serviceName, "0.1"); + + // set url + Config config = Utils.getConfig(); + String url = String.format( + PathUrls.SERVICE_FORWARDING_PATHS, + config.getCatalogBeHost(), + config.getCatalogBePort(), + servicePaths.right.getUniqueId() + ); + String userId = sdncUserDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse restResponse = http.httpSendGet(url, headersMap); + assertEquals("Check API response code for GetServiceForwardingPathsAPI call", HttpStatus.SC_OK, restResponse.getErrorCode().intValue()); + return restResponse; + } + + public static RestResponse getServicePathLinkMapAPI(String serviceName) throws Exception { + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + // get service + Pair<RestResponse, ServiceReqDetails> servicePaths = getServiceIDByNameAndVersion(serviceName, "0.1"); + + // set url + Config config = Utils.getConfig(); + String url = String.format( + PathUrls.SERVICE_PATH_LINK_MAP, + config.getCatalogBeHost(), + config.getCatalogBePort(), + servicePaths.right.getUniqueId() + ); + + String userId = sdncUserDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse restResponse = http.httpSendGet(url, headersMap); + assertEquals("Check API response code for GetServiceForwardingPathsAPI call", HttpStatus.SC_OK, restResponse.getErrorCode().intValue()); + return restResponse; + } + + public static Pair<RestResponse, ServiceReqDetails> getServicePathsAPI(String serviceName) throws Exception { + User sdncUserDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // get service + Pair<RestResponse, ServiceReqDetails> servicePaths = getServiceIDByNameAndVersion(serviceName, "0.1"); + + // set url + Config config = Utils.getConfig(); + String url = String.format( + PathUrls.GET_SERVICE_PATHS, + config.getCatalogFeHost(), + config.getCatalogFePort(), + servicePaths.right.getUniqueId()); + + String userId = sdncUserDetails.getUserId(); + + Map<String, String> headersMap = prepareHeadersMap(userId); + + HttpRequest http = new HttpRequest(); + RestResponse restResponse = http.httpSendGet(url, headersMap); + assertEquals("Check API response code for GetServiceForwardingPathsAPI call", HttpStatus.SC_OK, restResponse.getErrorCode().intValue()); + return new Pair<>(restResponse, servicePaths.right); + } + + public static Pair<RestResponse, OnboardItemObject> createNewItemVersion(String itemId, String itemVersion, String description, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format( + PathUrls.CREATE_NEW_ITEM_VERSION, + config.getCatalogBeHost(), + config.getCatalogBePort(), + itemId, itemVersion); + String userId = user.getUserId(); + OnboardItemObject onboardItemObject = new OnboardItemObject(); + + onboardItemObject.setCreationMethod("major"); + onboardItemObject.setDescription(description); + + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + Gson gson = new Gson(); + String body = gson.toJson(onboardItemObject); + + RestResponse response = http.httpSendPost(url, body, headersMap); + + onboardItemObject.setItemId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "id")); + onboardItemObject.setName(ResponseParser.getValueFromJsonResponse(response.getResponse(), "name")); + onboardItemObject.setBaseId(ResponseParser.getValueFromJsonResponse(response.getResponse(), "baseId")); + onboardItemObject.setStatus(ResponseParser.getValueFromJsonResponse(response.getResponse(), "status")); + + return new Pair<>(response, onboardItemObject); + } + + public static RestResponse updateVendorSoftwareProduct(VendorSoftwareProductObject vendorSoftwareProductObject, User user) throws Exception { + Config config = Utils.getConfig(); + String url = String.format( + PathUrls.UPDATE_VENDOR_SOFTWARE_PRODUCT, + config.getCatalogBeHost(), + config.getCatalogBePort(), + vendorSoftwareProductObject.getVspId(), + vendorSoftwareProductObject.getComponentId()); + String userId = user.getUserId(); + VendorSoftwareProductObject updateVendorSoftwareProductObject = new VendorSoftwareProductObject(); + + updateVendorSoftwareProductObject.setName(vendorSoftwareProductObject.getName()); + updateVendorSoftwareProductObject.setDescription(vendorSoftwareProductObject.getDescription()); + updateVendorSoftwareProductObject.setCategory(vendorSoftwareProductObject.getCategory()); + updateVendorSoftwareProductObject.setSubCategory(vendorSoftwareProductObject.getSubCategory()); + updateVendorSoftwareProductObject.setVendorName(vendorSoftwareProductObject.getVendorName()); + updateVendorSoftwareProductObject.setVendorId(vendorSoftwareProductObject.getVendorId()); + updateVendorSoftwareProductObject.setIcon(vendorSoftwareProductObject.getIcon()); + updateVendorSoftwareProductObject.setLicensingData(vendorSoftwareProductObject.getLicensingData()); + updateVendorSoftwareProductObject.setLicensingVersion(vendorSoftwareProductObject.getLicensingVersion()); + + Map<String, String> headersMap = prepareHeadersMap(userId); + HttpRequest http = new HttpRequest(); + Gson gson = new Gson(); + String body = gson.toJson(updateVendorSoftwareProductObject); + + return http.httpSendPut(url, body, headersMap); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathValidations.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathValidations.java new file mode 100644 index 0000000000..128438a51b --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/AmdocsComplexService/PathValidations.java @@ -0,0 +1,360 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.AmdocsComplexService; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import org.apache.commons.lang.RandomStringUtils; +import org.json.JSONObject; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.execute.devCI.ArtifactFromCsar; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.utilities.DownloadManager; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.execute.setup.ArtifactsCorrelationManager; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.openqa.selenium.WebElement; + +import java.io.File; +import java.util.*; +import java.util.stream.Collectors; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotSame; + + +public class PathValidations { + + + public static final int NUMBER_OF_LINKS = 5; + public static final int NUMBER_OF_LINES = 3; + public static final int NUMBER_OF_LINES_TO_DELETE = 1; + + public static String[] validateServiceExtendedPath(String vspName) throws Exception { + PathUtilities.linkVFs(vspName, NUMBER_OF_LINKS); + PathUtilities.openCreatePath(); + String pathName = "name1"; + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + PathValidations.extendPath(NUMBER_OF_LINES); + //delete line + PathUtilities.deleteLines(NUMBER_OF_LINES_TO_DELETE, NUMBER_OF_LINES); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + ExtentTestActions.log(Status.INFO, "path has been created"); + PathValidations.checkPathFilter(pathName, true); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.PATH_MENU_BUTTON.getValue() + "']/parent::*").get(0).click(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue()); + String PathListName1 = GeneralUIUtils.findByText(pathName).getText(); + // edit path + String newPathName = "name2"; + PathUtilities.editPathName(pathName, newPathName); + + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.PATH_MENU_BUTTON.getValue() + "']/parent::*").get(0).click(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue()); + String PathListName2 = GeneralUIUtils.findByText(newPathName).getText(); + + // assert names changed + assertNotSame("path name expected to change after edit but did not", PathListName1, PathListName2); + + // delete path + int paths_before_deletion = GeneralUIUtils.findElementsByXpath("//*[text()='" + newPathName + "']/parent::*//span").size(); + GeneralUIUtils.findElementsByXpath(newPathName).get(1).click(); + GeneralUIUtils.ultimateWait(); + int paths_after_deletion = GeneralUIUtils.findElementsByXpath("//*[text()='" + newPathName + "']/parent::*//span").size(); + assertNotSame("path expected to be deleted but did not", paths_after_deletion, paths_before_deletion); + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "Path has been created"); + // check that path got deleted in the path filter list + PathValidations.checkPathFilter(newPathName, false); + return new String[]{pathName, newPathName}; + } + + public static String[] validateComplexExtendedPath(String[] services) throws Exception { + PathUtilities.linkServices(services[0], services[1], NUMBER_OF_LINKS); + PathUtilities.openCreatePath(); + String pathName = "name1"; + PathUtilities.insertValues(pathName, "pathProtocol1", "pathPortNumbers"); + PathUtilities.selectFirstLineParam(); + PathValidations.extendPath(NUMBER_OF_LINES); + //delete line + PathUtilities.deleteLines(NUMBER_OF_LINES_TO_DELETE, NUMBER_OF_LINES); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + ExtentTestActions.log(Status.INFO, "path has been created"); + PathUtilities.openPathList(); + String PathListName1 = GeneralUIUtils.findByText(pathName).getText(); + String newPathName = "name2"; + PathUtilities.editPathName(pathName, newPathName); + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.PATH_MENU_BUTTON.getValue() + "']/parent::*").get(0).click(); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_BUTTON.getValue()); + String PathListName2 = GeneralUIUtils.findByText(newPathName).getText(); + + // assert names changed + assertNotSame("path name expected to change after edit but did not", PathListName1, PathListName2); + + // delete path + int paths_before_deletion = GeneralUIUtils.findElementsByXpath("//*[text()='" + newPathName + "']/parent::*//span").size(); + GeneralUIUtils.findElementsByXpath("//*[text()='" + newPathName + "']/parent::*//span").get(1).click(); + GeneralUIUtils.ultimateWait(); + + int paths_after_deletion = GeneralUIUtils.findElementsByXpath("//*[text()='" + newPathName + "']/parent::*//span").size(); + assertNotSame("path expected to be deleted but did not", paths_after_deletion, paths_before_deletion); + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue()); + PathValidations.validateServicePath(services[2], pathName); + PathValidations.validateServicePath(services[2], newPathName); + SetupCDTest.getExtendTest().log(Status.INFO, "Paths have been validated"); + return new String[]{pathName, newPathName}; + } + + public static void createPathNumOfRows(int numOfPathRows) throws Exception { + final int numberOfRandomCharacters = 8; + PathUtilities.openCreatePath(); + PathUtilities.insertValues("extended" + RandomStringUtils.randomAlphanumeric(numberOfRandomCharacters), "pathProtocol1", "pathPortNumbers1"); + PathUtilities.selectFirstLineParam(); + extendPath(numOfPathRows); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "Path with " + numOfPathRows + " rows has been created"); + } + + public static void extendPath(int numOfLines) throws Exception { + for (int i = 0; i < numOfLines; i++) { + String check; + String index = Integer.toString(i + 2); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.EXTEND_BUTTON.getValue()); + + List<WebElement> linkSrcs = GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_SOURCE.getValue() + "']//select"); + List<WebElement> linkSrcCPs = GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_SOURCE_CP.getValue() + "']//select"); + List<WebElement> linkTargets = GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_TARGET.getValue() + "']//select"); + List<WebElement> linkTargetCPs = GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_TARGET_CP.getValue() + "']//select"); + for (int j = 0; j < i + 2; j++) { + validateExtendedPathDisabledButtons(linkSrcs, j, "Source should be disabled. open bug to UI team"); + check = linkSrcCPs.get(j).getAttribute("class"); + validateElementDisabledAttribute(check, "Source connection point"); + } + for (int j = 0; j < i + 1; j++) { + check = linkTargets.get(j).getAttribute("class"); + validateElementDisabledAttribute(check, "Target"); + check = linkTargetCPs.get(j).getAttribute("class"); + validateElementDisabledAttribute(check, "Target connection point"); + } + List<WebElement> choices = GeneralUIUtils.findElementsByXpath("//*[" + index + "]/*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_TARGET.getValue() + "']//option"); + choices.get((new Random()).nextInt(choices.size())).click(); + choices = GeneralUIUtils.findElementsByXpath("//*[" + index + "]/*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.LINK_TARGET_CP.getValue() + "']//option"); + choices.get((new Random()).nextInt(choices.size())).click(); + } + } + + public static void validateElementDisabledAttribute(String check, String param) throws Exception { + assertEquals(param + " of last lines should be disabled", check.contains("disabled"), true); + } + + public static void validateExtendedPathDisabledButtons(List<WebElement> linkSrcs, int i, String errMsg) throws Exception { + String check = linkSrcs.get(i).getAttribute("class"); + assertEquals(errMsg, check.contains("disabled"), true); + } + + public static void validatePathListIsEmpty() throws Exception { + PathUtilities.openPathList(); + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_DELETE.getValue()); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "path list is empty"); + } + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.CLOSE.getValue()); + } + + public static void AssertNameChangeFromPathList(String pathListName1, String pathListName2) throws Exception { + assertNotSame("path name is expected to change after edit", pathListName1, pathListName2); + } + + public static void ValidateAndDeletePathFromPathList(String pathName) throws Exception { + // count paths + List<WebElement> path_list_name = GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_NAME.getValue()); + // delete paths + List<WebElement> path_delete = GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_DELETE.getValue()); + int paths_before_deletion = 0; + for (int i = 0; i < path_list_name.size(); i++) { + if (path_list_name.get(i).getText().equals(pathName)) { + paths_before_deletion++; + path_delete.get(i).click(); + } + } + int paths_after_deletion = 0; + List<WebElement> path_list_name2; + try { + path_list_name2 = GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.ComplexServiceAmdocs.PATH_LIST_NAME.getValue()); + for (WebElement path_list_element : path_list_name2) { + if (path_list_element.getText().equals(pathName)) { + paths_after_deletion++; + } + } + } catch (Exception ignore) { + } + // assert deletion + assertNotSame("path is expected to be deleted", paths_after_deletion, paths_before_deletion); + } + + public static void checkPathFilter(String pathName, boolean isFound) throws Exception { + List<WebElement> pathFilterList = GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.SERVICE_PATH_SELECTOR.getValue() + "']//option"); + GeneralUIUtils.ultimateWait(); + if (isFound) { + for (int i = 0; i < pathFilterList.size(); i++) { + String element_text = pathFilterList.get(i).getText(); + if (element_text.equals(pathName)) { + break; + } + assertNotSame("path filter list is missing a path", i, pathFilterList.size() - 1); + } + } else { + for (WebElement aPathFilterList : pathFilterList) { + String element_text = aPathFilterList.getText(); + assertNotSame("path filter list is has a path that should be deleted", element_text, pathName); + } + } + SetupCDTest.getExtendTest().log(Status.INFO, "path list filter check passed"); + } + + public static void AssertCreatePath() throws Exception { + String check = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ComplexServiceAmdocs.CREATE_BUTTON.getValue()).getAttribute("disabled"); + assertEquals("create button path should be disabled", check, "true"); + } + + public static void AssertCreatedPathExistInCompositionPage(String pathName) throws Exception { + checkPathFilter(pathName, true); + PathUtilities.openPathList(); + + // assert path is in the list + GeneralUIUtils.findByText(pathName).getText(); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_CLOSE.getValue()); +// GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, "Path is in the path list"); +// GeneralUIUtils.ultimateWait(); + } + + public static void AssertExtendPath() throws Exception { + String check = GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.ComplexServiceAmdocs.EXTEND_BUTTON.getValue()).get(0).getAttribute("class"); + assertEquals("Extend button should be disabled", check, "disabled"); + } + + public static Pair<RestResponse, ServiceReqDetails> validateServicePath(String serviceName, String name) throws Exception { + Pair<RestResponse, ServiceReqDetails> servicePaths = PathUtilities.getServicePathsAPI(serviceName); + String response = servicePaths.left.getResponse(); + + JSONObject jsonResponse = new JSONObject(response); + JSONObject forwardingPaths = jsonResponse.getJSONObject("forwardingPaths"); + Boolean validation_complete = Boolean.FALSE; + for (Iterator it = forwardingPaths.keys(); it.hasNext(); ) { + Object key = it.next(); + String keyStr = (String) key; + JSONObject forwardingPath = forwardingPaths.getJSONObject(keyStr); + if (forwardingPath.getString("name").equals(name)) { + JSONObject pathElements = forwardingPath.getJSONObject("pathElements"); + Boolean empty = pathElements.getBoolean("empty"); + assertEquals("assert pathElements are not empty", empty, Boolean.FALSE); + validation_complete = Boolean.TRUE; + break; + } + } + assertEquals("validation success", validation_complete, Boolean.TRUE); + return servicePaths; + } + + public static void ValidateThereIsNoErrorMessage() throws Exception { + try { + GeneralUIUtils.findElementsByXpath("//*[@data-tests-id='" + DataTestIdEnum.ComplexServiceAmdocs.OK.getValue() + "']"); + throw new Exception("element should not be found"); + } catch (Exception e) { + if (e.getMessage().equals("element should not be found")) { + throw e; + } + } + } + + public static void validateEditToExistingName(String firstPathName, String secondPathName) throws Exception { + PathUtilities.openPathList(); + PathUtilities.editPathName(secondPathName, firstPathName); + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } catch (Exception e) { + throw new Exception("when creating another path with duplicate name, expected error did not appear"); + } + PathUtilities.openPathList(); + PathUtilities.editPathName(secondPathName, firstPathName + " "); + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } catch (Exception e) { + throw new Exception("space in beggining or end does not count. when creating another path with duplicate name, expected error did not appear"); + } + PathUtilities.openPathList(); + PathUtilities.editPathName(secondPathName, " " + firstPathName); + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ComplexServiceAmdocs.OK.getValue()); + } catch (Exception e) { + throw new Exception("space in beggining or end does not count. when creating another path with duplicate name, expected error did not appear"); + } + PathUtilities.openPathList(); + PathUtilities.editPathProtocol(secondPathName, "pathProtocol2"); + } + + public static void validateNameWithSpaces(String pathName, String vspName) throws Exception { + PathUtilities.createPath(pathName + " ", vspName); + PathUtilities.openPathList(); + PathUtilities.editPathName(pathName, "newName"); + PathUtilities.createPathWithoutLink(" " + pathName, vspName); + PathUtilities.openPathList(); + PathUtilities.editPathName(pathName, "newName2"); + } + + public static void importAndVerifyVSP(VendorSoftwareProductObject createVendorSoftwareProduct, String filepath, String vnfFile) throws Exception { + DownloadManager.downloadCsarByNameFromVSPRepository(createVendorSoftwareProduct.getName(), createVendorSoftwareProduct.getVspId()); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + + OnboardingUiUtils.importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + // Verify deployment artifacts + Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); + + LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment")); + ArtifactsCorrelationManager.addVNFartifactDetails(vnfFile, deploymentArtifacts); + + List<String> heatEnvFilesFromCSAR = deploymentArtifacts.stream().filter(e -> e.getType().equals("HEAT_ENV")). + map(e -> e.getFileName()). + collect(Collectors.toList()); + + OnboardingUiUtils.validateDeploymentArtifactsVersion(deploymentArtifacts, heatEnvFilesFromCSAR); + + DeploymentArtifactPage.verifyArtifactsExistInTable(filepath, vnfFile); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/AdminUserManagment.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/AdminUserManagment.java new file mode 100644 index 0000000000..d2c0aff1fc --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/AdminUserManagment.java @@ -0,0 +1,265 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.apache.http.HttpStatus; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.AdminGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.AdminWorkspaceUIUtilies; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.UserRestUtils; +import org.onap.sdc.frontend.ci.tests.verificator.ErrorMessageUIVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.UserManagementVerificator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.List; + +public class AdminUserManagment extends SetupCDTest { + + @DataProvider(name = "searchValues") + private Object[][] searchString() { + User newUser = createNewUserUsingAPI(); + GeneralUIUtils.getDriver().navigate().refresh(); + return new Object[][]{{newUser.getUserId(), newUser}, {newUser.getFirstName(), newUser}, {newUser.getLastName(), newUser}, {newUser.getEmail(), newUser}}; + } + + //TC915101 + @Test(dataProvider = "searchValues") + public void searchUserByCriterionsTest(String searchCriterion, User user) throws IOException { + setLog(searchCriterion); + AdminWorkspaceUIUtilies.searchForUser(searchCriterion); + UserManagementVerificator.validateFirstRowDisplayedCorrectly(user); + } + + //TC915100 + @Test + public void createNewUserTest() throws Exception { + + String userId = generateValidUserId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + GeneralUIUtils.ultimateWait(); + UserManagementVerificator.validateUserCreated(userId, userRole); + } + + //TC922253 + @Test + public void createNewUser_MacIdTest() throws Exception { + + String macId = generateValidMacId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(macId, userRole); + GeneralUIUtils.ultimateWait(); + UserManagementVerificator.validateUserCreated(macId, userRole); + } + + //TC922253 + @Test + public void createExistingUserTest() { + String userId = generateValidUserId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + ExtentTestActions.log(Status.INFO, "Trying to create the same user once again."); + GeneralUIUtils.ultimateWait(); // extra wait, necessary for system with large user list + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.USER_ALREADY_EXIST); + } + + + // design changed and now one letter user should exist + //TC922253 + @Test(enabled = true) + public void createInvalidMacIdTest() { + + ExtentTestActions.log(Status.INFO, "Open bug 324032"); + + String macId = generateValidMacId(); + StringBuilder invalidMacId = new StringBuilder(macId); + invalidMacId.setCharAt(0, 'a'); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + ExtentTestActions.log(Status.INFO, "Trying to create an invalid macId."); + AdminWorkspaceUIUtilies.createNewUser(invalidMacId.toString(), userRole); + GeneralUIUtils.ultimateWait(); + ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.INVALID_USER_ID); + } + + //TC922253 + @Test + public void specialCharInUserIdTest() { + String expectedErrorMsg = "User id not valid."; + String userId = generateValidUserId(); + StringBuilder invalidUserId = new StringBuilder(userId); + invalidUserId.setCharAt(1, '#'); + ExtentTestActions.log(Status.INFO, String.format("Trying to create an invalid user with special character (%s)", userId)); + AdminGeneralPage.getUserManagementTab().setNewUserBox(invalidUserId.toString()); + ExtentTestActions.log(Status.INFO, "Validating an error message is displayed as a result of invalid character."); + List<WebElement> inputErrors = null; + int inputErrorsSize = 0; + + try { + WebElement inputField = GeneralUIUtils.getWebElementByClassName("input-error"); + ExtentTestActions.log(Status.INFO, String.format("Validating the message is : '%s'", expectedErrorMsg)); + inputErrors = inputField.findElements(By.className("ng-scope")); + inputErrorsSize = inputErrors.size(); + for (WebElement err : inputErrors) { + String actualErrorMessage = err.getText(); + if (actualErrorMessage.equals(expectedErrorMsg)) { + inputErrorsSize--; + } + } + } catch (Exception e) { + ExtentTestActions.log(Status.INFO, "Did not find an error input."); + Assert.fail("Did not find an error message input."); + } + + Assert.assertEquals(inputErrors.size() - 1, inputErrorsSize, "Did not find an error : " + expectedErrorMsg); + } + + + //TC915101 + @Test + public void searchForUserByRoleTest() { + String userId = generateValidUserId(); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(userId, userRole); + AdminWorkspaceUIUtilies.searchForUser(userRole.name()); + List<WebElement> allRows = GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.UserManagementEnum.USER_ID.getValue()); + ExtentTestActions.log(Status.INFO, String.format("Found %s rows, looking for the user %s.", allRows.size(), userId)); + int rowsCount = allRows.size(); + for (WebElement allRow : allRows) { + String userIdFromTable = GeneralUIUtils.getTextContentAttributeValue(allRow); + if (userIdFromTable.equals(userId)) { + rowsCount--; + break; + } + } + Assert.assertEquals(allRows.size() - 1, rowsCount, "Did not find a row with the userId " + userId); + } + + //TC915102 + @Test + public void modifyUserRoleTest() { + User user = new User(); + user.setUserId(generateValidUserId()); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(user.getUserId(), userRole); + UserRoleEnum updatedUserRole = UserRoleEnum.TESTER; + AdminWorkspaceUIUtilies.updateUserRole(0, updatedUserRole); + UserManagementVerificator.validateUserRoleUpdated(0, updatedUserRole); + UserManagementVerificator.validateUserRoleUpdatedViaRest(user, getUser(), updatedUserRole); + } + + //TC915103 + @Test + public void deleteUserTest() { + User user = new User(); + user.setUserId(generateValidUserId()); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(user.getUserId(), userRole); + AdminWorkspaceUIUtilies.deleteFirstRow(); + UserManagementVerificator.validateUserIdNotFound(user.getUserId()); + UserManagementVerificator.validateUserNotFoundViaRest(user, getUser()); + } + + //TC951428 + @Test + public void modifyUserRoleWithTaskInHand_Checkout() throws Exception { + User newUser = new User(); + newUser.setUserId(generateValidUserId()); + UserRoleEnum userRole = UserRoleEnum.DESIGNER; + AdminWorkspaceUIUtilies.createNewUser(newUser.getUserId(), userRole); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, newUser); + ExtentTestActions.log(Status.INFO, "Creating a new VF named " + resourceMetaData.getName() + " with the user " + newUser.getUserId()); + RestResponse createResourceResp = ResourceRestUtils.createResource(resourceMetaData, newUser); + Assert.assertEquals(createResourceResp.getErrorCode().intValue(), HttpStatus.SC_CREATED, "Did not succeed to create a VF"); + + UserRoleEnum updatedUserRole = UserRoleEnum.TESTER; + AdminWorkspaceUIUtilies.updateUserRole(0, updatedUserRole); + + ErrorMessageUIVerificator.validateErrorMessage(ActionStatus.CANNOT_UPDATE_USER_WITH_ACTIVE_ELEMENTS); + } + + + private static String generateValidUserId() { + final int charsPatternLength = 2; + final int digitsPatternLength = 4; + String charsPattern = "abcdefghijklmnopqrstuvwxyz"; + String digitPatter = "0123456789"; + String chars = ResourceUIUtils.buildStringFromPattern(charsPattern, charsPatternLength); + String digits = ResourceUIUtils.buildStringFromPattern(digitPatter, digitsPatternLength); + return chars + digits; + } + + private String generateValidMacId() { + final int digitsPatternLength = 5; + String digitPatter = "0123456789"; + String digits = ResourceUIUtils.buildStringFromPattern(digitPatter, digitsPatternLength); + return "m" + digits; + } + + private User createNewUserUsingAPI() { + UserRoleEnum role = UserRoleEnum.DESIGNER; + String userId = generateValidUserId(); + User userByEnv = new User(generateValidUserId(), generateValidUserId(), userId, generateValidUserId() + "@intl.sdc.com", role.name(), null); + User adminUser = getUserByEnv(UserRoleEnum.ADMIN); + try { + RestResponse createUserResp = UserRestUtils.createUser(userByEnv, adminUser); + Assert.assertEquals(createUserResp.getErrorCode().intValue(), HttpStatus.SC_CREATED, "Did not succeed to create a new user using API."); + } catch (IOException e) { + e.printStackTrace(); + } + return userByEnv; + } + + + private User getUserByEnv(UserRoleEnum userRole) { + try { + return getUser(userRole); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.ADMIN; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Annotation.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Annotation.java new file mode 100644 index 0000000000..0ba9b065fe --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Annotation.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.File; + +import static org.assertj.core.api.Assertions.assertThat; + +public class Annotation extends SetupCDTest { + private String filePath; + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath("SRIOV"); + } + + @Test + public void importCsarWithAnnotationVerifyDownloadYmlContainsAnnotationSection() throws Exception { + String fileName = "SIROV_annotations_VSP.csar"; + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, + NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfFromCsar(vfMetaData, filePath, fileName, getUser()); + getExtendTest().log(Status.INFO, "Csar with annotations imported successfully."); + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.TOSCA_MODEL.getValue()); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + ToscaDefinition toscaMainVfDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(latestFilefromDir); + assertTrueAnnotationTestSuite(toscaMainVfDefinition); + getExtendTest().log(Status.INFO, "Success to validate the ToscaMainYaml contains annotation type source with properties."); + } + + + public void assertTrueAnnotationTestSuite(ToscaDefinition toscaMainVfDefinition) { + assertThat(toscaMainVfDefinition.getTopology_template().getInputs().get("availabilityzone_name").annotations).containsKey("source"); + assertThat(toscaMainVfDefinition.getTopology_template().getInputs().get("availabilityzone_name").getAnnotations().get("source").getType()).isEqualTo("org.openecomp.annotations.Source"); + assertThat(toscaMainVfDefinition.getTopology_template().getInputs().get("availabilityzone_name").getAnnotations().get("source").getProperties().get("source_type")).isEqualTo("HEAT"); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ArchiveRestoreTest.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ArchiveRestoreTest.java new file mode 100644 index 0000000000..1b0a3ed14f --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ArchiveRestoreTest.java @@ -0,0 +1,241 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.OpsOperationPage; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +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.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.GovernorOperationPage; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.HomeUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.testng.annotations.Test; + +import static org.testng.AssertJUnit.assertTrue; + +public class ArchiveRestoreTest extends SetupCDTest { + + private User sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + + @Test + public void updateVSP_WhenVF_Archived() throws Throwable { + + String vnfFile1 = "1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip"; + String vnfFile2 = "2-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0_Added2TestParameters.zip"; + +// 1. Import VSP v1.0 + String filePath = FileHandling.getUpdateVSPVnfRepositoryPath(); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", vendorLicenseModel + .getVendorLicenseName())); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile1)); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, this.sdncDesignerDetails, + vendorLicenseModel, null); +// 2. Create VF from VSP, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); + getExtendTest().log(Status.INFO, String.format("Certify the VF")); +// 3. Create Service add to it the certified VF and certify the Service v1.0 + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service")); +// 4. archive VF(1.0) + GeneralPageElements.clickArchivedButtonFromCatalog(resource.getName()); +// 5. service certification should send error message - unable to certify, service contains archived resource via UI + HomeUtils.findComponentAndClick(service.getName()); + GeneralPageElements.clickSubmitForTestingButtonErrorCase(service.getName()); +// 6. Update VSP to v2.0 - onboard level + getExtendTest().log(Status.INFO, "Upgrading the VSP with new file: " + vnfFile2); + VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails, filePath, vnfFile2); + getExtendTest().log(Status.INFO, String.format("Validating VSP %s upgrade to version 2.0: ", vnfFile2)); + VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails); +// 7. Update the VF from VSP when it archived and restore - via UI + getExtendTest().log(Status.INFO, String.format("Going to update VF %s with VSP v2.0", resourceReqDetails.getName())); + CompositionPage.moveToHomeScreen(); + HomePage.showVspRepository(); + OnboardingUiUtils.updateVSP(vendorSoftwareProductObject, true); +// 8. Certify and update restored VF from with VSP v2.0 + GeneralPageElements.clickCertifyButton(resource.getName()); +// 9. Update the Service with the VFi version 2.0 and certify + HomeUtils.findComponentAndClick(service.getName()); + GeneralPageElements.clickSubmitForTestingButton(service.getName()); + } + + // https://sdp.web.att.com/fa3qm1/web/console/Application_Development_Tools_QM_20.20.01#action=com.ibm.rqm.planning.home.actionDispatcher&subAction=viewTestScript&id=896098 + @Test + public void certifyVF_WhenVSP_Archived() throws Exception { + + String vnfFile1 = "1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip"; + +// 1. Import VSP v1.0 + String filePath = FileHandling.getUpdateVSPVnfRepositoryPath(); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", vendorLicenseModel + .getVendorLicenseName())); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile1)); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, this.sdncDesignerDetails, + vendorLicenseModel, null); +// 2. Create VF from VSP, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); + getExtendTest().log(Status.INFO, String.format("Certify the VF")); +// 3. Archive VSP (onboarding page-Amdocs side) + getExtendTest().log(Status.INFO, String.format("Going to archive component OB side: %s", resource.getName())); + VendorSoftwareProductRestUtils.archiveVendorSoftwareProduct(vendorSoftwareProductObject, sdncDesignerDetails); + getExtendTest().log(Status.INFO, String.format("Succeed to archive component %s, OB side", resource.getName())); +// 4. chekout resource and check that VF is archived + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + HomeUtils.findComponentAndClick(resource.getName()); + GeneralPageElements.clickCheckoutButton(); + resource = AtomicOperationUtils.getResourceObject(resource.getUniqueId()); + getExtendTest().log(Status.INFO, String.format("Going to validate is VSP archived: %s", resource.getName())); + assertTrue("Validate isVspArchived flag, expected: true, but was: " + resource.isVspArchived(), resource.isVspArchived().equals(true)); + String expectedText = "VSP is archived"; + getExtendTest().log(Status.INFO, String.format("Going to validate text box message, expected: %s", expectedText)); + String actualElementText = GeneralPageElements.getWebElementTextByTestId(DataTestIdEnum.ResourceMetadataEnum.SELECT_VSP.getValue()); + assertTrue("Validate text box message, expected: [" + expectedText + "], but was: " + actualElementText, actualElementText.equals(expectedText)); +// 5. certify new resource - should fail, via API + getExtendTest().log(Status.INFO, String.format("Going to certify archived on OB side resource %s , expected failure certification", resource.getName())); + GeneralPageElements.clickCertifyButtonNoUpgradePopupDismissErrorCase(resource.getName()); +// 6. restore + getExtendTest().log(Status.INFO, String.format("Going to restore component OB side: %s", resource.getName())); + VendorSoftwareProductRestUtils.restoreVendorSoftwareProduct(vendorSoftwareProductObject, sdncDesignerDetails); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Succeed to restore component %s, OB side", resource.getName())); +// 7. certify - should pass + getExtendTest().log(Status.INFO, String.format("Going to certify resource %s ", resource.getName())); + GeneralPageElements.clickCertifyButtonNoUpgradePopupDismiss(resource.getName()); + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "2.0"); + assertTrue("Validate isVspArchived flag, expected: false, but was: " + resource.isVspArchived(), resource.isVspArchived().equals(false)); + } + + @Test + public void distributeServiceIncludedArchivedResource() throws Exception { + + String vnfFile1 = "1-2017-404_vUSP_vCCF_AIC3.0-(VOIP)_v6.0.zip"; +// 1. Import VSP v1.0 + String filePath = FileHandling.getUpdateVSPVnfRepositoryPath(); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", vendorLicenseModel + .getVendorLicenseName())); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile1)); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, this.sdncDesignerDetails, + vendorLicenseModel, null); +// 2. Create VF from VSP, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + getExtendTest().log(Status.INFO, String.format("Certify the VF")); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); +// 3. Create Service add to it the certified VF and certify the Service v1.0 + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(service.getName()); + GovernorOperationPage.approveService(service.getName()); +// 4. archive VF(1.0) + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralPageElements.clickArchivedButtonFromCatalog(resource.getName()); +// 5. Distribute service - should pass + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(service.getName()); + OpsOperationPage.distributeService(); + + } + + + @Test + public void certificationOfArchivedCR() throws Exception { + + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.CR, getUser()); + ResourceUIUtils.createCR(resourceReqDetails, sdncDesignerDetails); + GeneralPageElements.clickCertifyButtonNoUpgradePopupDismiss(resourceReqDetails.getName()); + GeneralUIUtils.ultimateWait(); + Resource resource = (Resource) AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceReqDetails.getName(), "1.0"); +// 1. Create Service add to it the certified CR and certify the Service v1.0 + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, String.format("Adding CR instance to Service")); +// 2. archive CR(1.0) + GeneralPageElements.clickArchivedButtonFromCatalog(resource.getName()); +// 3. service certification should send error message - unable to certify, service contains archived resource via UI + HomeUtils.findComponentAndClick(service.getName()); + GeneralPageElements.clickSubmitForTestingButtonErrorCase(service.getName()); +// 4. restore CR + GeneralPageElements.restoreComponentFromArchivedCatalog(resource.getName()); +// 5. Certify and update restored CR(v2.0) + GeneralPageElements.clickCheckoutButton(); + GeneralPageElements.clickCertifyButton(resource.getName()); +// 6. Update the Service with the CRi version 2.0 and certify service + HomeUtils.findComponentAndClick(service.getName()); + GeneralPageElements.clickSubmitForTestingButton(service.getName()); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CatalogLeftPanelTest.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CatalogLeftPanelTest.java new file mode 100644 index 0000000000..d4539b7f01 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CatalogLeftPanelTest.java @@ -0,0 +1,244 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.frontend.ci.tests.verificator.CatalogVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.CheckBoxStatusEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.TypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.openqa.selenium.WebElement; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.testng.AssertJUnit.assertTrue; + +@Test(singleThreaded = true) +public class CatalogLeftPanelTest extends SetupCDTest { + + private String filePath; + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath(""); + } + + private static String[] resourceTypes = Arrays.stream(ResourceTypeEnum.class.getEnumConstants()). + map(ResourceTypeEnum::name).toArray(String[]::new); + + private static String[] catalogTypes = {"RESOURCE", "SERVICE"}; + + private static Object[][] provideData(String[] arObj) { + Object[][] arObject = new Object[arObj.length][]; + + int index = 0; + for (Object obj : arObj) { + arObject[index++] = new Object[]{obj}; + } + return arObject; + } + + @DataProvider(name = "Resource_Type_List") + private static Object[][] resourceTypeList() { + // Extract names of constants from enum as array of Strings + ResourceTypeEnum[] resourceEnums = {ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC, ResourceTypeEnum.VL}; + String[] resourcesForTest = Arrays.stream(resourceEnums).map(ResourceTypeEnum::name).toArray(String[]::new); + return provideData(resourcesForTest); + } + + @DataProvider(name = "Type_List") + private static Object[][] typeList() { + // Extract names of constants from enum as array of Strings + Object[][] arObject = new Object[catalogTypes.length][]; + int index = 0; + for (String catalogType : catalogTypes) { + if (catalogType.equals("RESOURCE")) { + arObject[index++] = new Object[]{catalogType, resourceTypes}; + } else { + arObject[index++] = new Object[]{catalogType, new String[]{catalogType}}; + } + } + return arObject; + } + + @DataProvider(name = "Status_List") + private static Object[][] statusList() { + CheckBoxStatusEnum[] checkboxes = {CheckBoxStatusEnum.CERTIFIED, + CheckBoxStatusEnum.IN_DESIGN, + CheckBoxStatusEnum.DISTRIBUTED, + CheckBoxStatusEnum.IN_TESTING, + CheckBoxStatusEnum.READY_FOR_TESTING}; + Object[][] arObject = new Object[checkboxes.length][]; + int index = 0; + for (CheckBoxStatusEnum checkbox : checkboxes) { + if (checkbox.equals(CheckBoxStatusEnum.CERTIFIED)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.CERTIFIED, LifeCycleStateEnum.DISTRIBUTED, LifeCycleStateEnum.WAITING_FOR_DISTRIBUTION)}; + } else if (checkbox.equals(CheckBoxStatusEnum.IN_DESIGN)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.CHECKIN, LifeCycleStateEnum.CHECKOUT)}; + } else if (checkbox.equals(CheckBoxStatusEnum.DISTRIBUTED)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.DISTRIBUTED)}; + } else if (checkbox.equals(CheckBoxStatusEnum.IN_TESTING)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.IN_TESTING)}; + } else if (checkbox.equals(CheckBoxStatusEnum.READY_FOR_TESTING)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.READY_FOR_TESTING)}; + } + } + return arObject; + } + + // filter by Type Resource in catalog + @Test(dataProvider = "Type_List") + public void filterByType(String catalogType, String[] classValues) throws Exception { + setLog(catalogType); +// getExtendTest().setDescription(catalogType); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogFilterTypeChecBox(TypesEnum.valueOf(catalogType)); + CatalogVerificator.validateType(TypesEnum.valueOf(catalogType)); + } + + @Test(dataProvider = "Resource_Type_List") + public void filterByResourceType(String resourceType) throws Exception { + setLog(resourceType); +// getExtendTest().setDescription(resourceType); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogFilterTypeChecBox(TypesEnum.valueOf(resourceType)); + + CatalogVerificator.validateType(TypesEnum.valueOf(resourceType)); + } + + @Test(dataProvider = "Status_List") + public void filterByStatus(CheckBoxStatusEnum statusCheckbox, List<LifeCycleStateEnum> lifecycleStates) throws Exception { + setLog(statusCheckbox.name()); +// getExtendTest().setDescription(statusCheckbox.name()); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.CATEGORIES); + CatalogUIUtilitis.catalogFilterStatusChecBox(statusCheckbox); + //TODO check the test after removing lifecycle steps for resource + CatalogVerificator.validateStatus(lifecycleStates, statusCheckbox.name()); + } + + @Test + public void filterByUpperCategory() throws Exception { + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.TYPE); + + WebElement categoryCheckbox = CatalogUIUtilitis.clickOnUpperCategoryCheckbox(); + + CatalogVerificator.validateCategory(categoryCheckbox.getAttribute("textContent").trim()); + } + + @Test + public void filterByGenericDatabaseSubCategory() throws Exception { + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.TYPE); + + WebElement checkboxElement = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.CatalogPageLeftPanelSubCategoryCheckbox.DATABASE.getValue()).get(0); + String checkboxElementName = checkboxElement.getAttribute("textContent").trim(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s subcategory ...", checkboxElementName)); + GeneralUIUtils.clickOnAreaJS(checkboxElement); + CatalogVerificator.validateSubCategory("Generic", checkboxElementName); + } + + @Test(priority = 1) + public void lastUpdatedService() throws Exception { + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + List<WebElement> cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Expected : %s , Actual: %s", serviceMetadata.getName(), firstElementName), serviceMetadata.getName().equals(firstElementName)); + } + + @Test(priority = 17) + public void lastUpdatedResource() throws Exception { + // create resource + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + List<WebElement> cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Expected : %s , Actual: %s", vfMetaData.getName(), firstElementName), vfMetaData.getName().equals(firstElementName)); + } + + @Test(priority = 5) + public void fromCatalogCheckout() throws Exception { + // create resource + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + } + + @Test + public void keepSearchResultsInCatalogAfterBrowserBack() throws Exception { + ResourceReqDetails resourceMetadata = ElementFactory.getDefaultResource(); + ResourceUIUtils.createVF(resourceMetadata, getUser()); + ResourceGeneralPage.clickCheckinButton(resourceMetadata.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogSearchBox(resourceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(resourceMetadata.getName()); + + GeneralUIUtils.clickOnBrowserBackButton(); + + int numOfElementsInFilteredCatalog = CatalogVerificator.getNumberOfElementsFromCatalogHeader(); + assertTrue(String.format("Wrong number fo elements, Expected : %s , Actual: %s", 1, numOfElementsInFilteredCatalog), numOfElementsInFilteredCatalog == 1); + + List<WebElement> cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Expected : %s , Actual: %s", resourceMetadata.getName(), firstElementName), resourceMetadata.getName().equals(firstElementName)); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CatalogLeftPanelTestWithTime.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CatalogLeftPanelTestWithTime.java new file mode 100644 index 0000000000..9a44156d1a --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CatalogLeftPanelTestWithTime.java @@ -0,0 +1,294 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.frontend.ci.tests.verificator.CatalogVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.CheckBoxStatusEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.TypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.openqa.selenium.WebElement; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.testng.AssertJUnit.assertTrue; + +@Test(singleThreaded = true) +public class CatalogLeftPanelTestWithTime extends SetupCDTest { + + private static final int REGULAR_TEST_RUN_TIME = 400; + private String filePath; + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath(""); + } + + private static String[] resourceTypes = Arrays.stream(ResourceTypeEnum.class.getEnumConstants()). + map(ResourceTypeEnum::name).toArray(String[]::new); + + private static String[] catalogTypes = {"RESOURCE", "SERVICE"}; + + private static Object[][] provideData(String[] arObj) { + Object[][] arObject = new Object[arObj.length][]; + + int index = 0; + for (Object obj : arObj) { + arObject[index++] = new Object[]{obj}; + } + return arObject; + } + + @DataProvider(name = "Resource_Type_List") + private static Object[][] resourceTypeList() { + // Extract names of constants from enum as array of Strings + ResourceTypeEnum[] resourceEnums = {ResourceTypeEnum.CP, ResourceTypeEnum.VF, ResourceTypeEnum.VFC, ResourceTypeEnum.VL}; + String[] resourcesForTest = Arrays.stream(resourceEnums).map(ResourceTypeEnum::name).toArray(String[]::new); + return provideData(resourcesForTest); + } + + @DataProvider(name = "Type_List") + private static Object[][] typeList() { + // Extract names of constants from enum as array of Strings + Object[][] arObject = new Object[catalogTypes.length][]; + int index = 0; + for (String catalogType : catalogTypes) { + if (catalogType.equals("RESOURCE")) { + arObject[index++] = new Object[]{catalogType, resourceTypes}; + } else { + arObject[index++] = new Object[]{catalogType, new String[]{catalogType}}; + } + } + return arObject; + } + + @DataProvider(name = "Status_List") + private static Object[][] statusList() { + CheckBoxStatusEnum[] checkboxes = {CheckBoxStatusEnum.CERTIFIED, + CheckBoxStatusEnum.IN_DESIGN, + CheckBoxStatusEnum.DISTRIBUTED, + CheckBoxStatusEnum.IN_TESTING, + CheckBoxStatusEnum.READY_FOR_TESTING}; + Object[][] arObject = new Object[checkboxes.length][]; + int index = 0; + for (CheckBoxStatusEnum checkbox : checkboxes) { + if (checkbox.equals(CheckBoxStatusEnum.CERTIFIED)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.CERTIFIED, LifeCycleStateEnum.DISTRIBUTED, LifeCycleStateEnum.WAITING_FOR_DISTRIBUTION)}; + } else if (checkbox.equals(CheckBoxStatusEnum.IN_DESIGN)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.CHECKIN, LifeCycleStateEnum.CHECKOUT)}; + } else if (checkbox.equals(CheckBoxStatusEnum.DISTRIBUTED)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.DISTRIBUTED)}; + } else if (checkbox.equals(CheckBoxStatusEnum.IN_TESTING)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.IN_TESTING)}; + } else if (checkbox.equals(CheckBoxStatusEnum.READY_FOR_TESTING)) { + arObject[index++] = new Object[]{checkbox, Arrays.asList(LifeCycleStateEnum.READY_FOR_TESTING)}; + } + } + return arObject; + } + + // filter by Type Resource in catalog + @Test(dataProvider = "Type_List") + public void filterByTypeWithTime(String catalogType, String[] classValues) throws Exception { + setLog(catalogType); + //Load catalog + Long actualTestRunTime = GeneralUIUtils.getAndValidateActionDuration(() -> + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG), REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog loading time is " + + actualTestRunTime + " seconds"); + //Filter by type + actualTestRunTime = Utils.getAndValidateActionDuration(() -> { + try { + CatalogUIUtilitis.catalogFilterTypeChecBox(TypesEnum.valueOf(catalogType)); + } catch (Exception e) { + e.printStackTrace(); + } + }, REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog filtering time is " + + actualTestRunTime + " seconds"); + //Validate number of elements after filtering + CatalogVerificator.validateType(TypesEnum.valueOf(catalogType)); + } + + @Test(dataProvider = "Resource_Type_List") + public void filterByResourceTypeWithTime(String resourceType) throws Exception { + setLog(resourceType); + //Load catalog + Long actualTestRunTime = Utils.getAndValidateActionDuration(() -> + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG), REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog loading time is " + + actualTestRunTime + " seconds"); + //Filter by resource type + actualTestRunTime = Utils.getAndValidateActionDuration(() -> { + try { + CatalogUIUtilitis.catalogFilterTypeChecBox(TypesEnum.valueOf(resourceType)); + } catch (Exception e) { + e.printStackTrace(); + } + }, REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog filtering time is " + + actualTestRunTime + " seconds"); + //Validate number of elements after filtering + CatalogVerificator.validateType(TypesEnum.valueOf(resourceType)); + } + + @Test(dataProvider = "Status_List") + public void filterByStatus(CheckBoxStatusEnum statusCheckbox, List<LifeCycleStateEnum> lifecycleStates) throws Exception { + setLog(statusCheckbox.name()); + //Load catalog + Long actualTestRunTime = Utils.getAndValidateActionDuration(() -> + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG), REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog loading time is " + + actualTestRunTime + " seconds"); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.CATEGORIES); + //Filter by resource type + actualTestRunTime = Utils.getAndValidateActionDuration(() -> CatalogUIUtilitis.catalogFilterStatusChecBox(statusCheckbox), REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog filtering time is " + + actualTestRunTime + " seconds"); + //TODO check the test after removing lifecycle steps for resource + //Validate number of elements after filtering + CatalogVerificator.validateStatus(lifecycleStates, statusCheckbox.name()); + } + + @Test + public void filterByUpperCategory() throws Exception { + //Load catalog + Long actualTestRunTime = Utils.getAndValidateActionDuration(() -> + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG), REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog loading time is " + + actualTestRunTime + " seconds"); + //Filter by Upper Category + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.TYPE); + actualTestRunTime = Utils.getAndValidateActionDuration(() -> CatalogUIUtilitis.clickOnUpperCategoryCheckbox(), REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog filtering time is " + + actualTestRunTime + " seconds"); + WebElement categoryCheckbox = CatalogUIUtilitis.getCategoryCheckbox(); + CatalogVerificator.validateCategory(categoryCheckbox.getAttribute("textContent").trim()); + } + + @Test + public void filterByGenericDatabaseSubCategory() throws Exception { + //Load catalog + Long actualTestRunTime = Utils.getAndValidateActionDuration(() -> + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG), REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog loading time is " + + actualTestRunTime + " seconds"); + CatalogUIUtilitis.clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle.TYPE); + WebElement checkboxElement = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.CatalogPageLeftPanelSubCategoryCheckbox.DATABASE.getValue()).get(0); + String checkboxElementName = checkboxElement.getAttribute("textContent").trim(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s subcategory ...", checkboxElementName)); + //Filter by sub category + actualTestRunTime = Utils.getAndValidateActionDuration(() -> { + try { + GeneralUIUtils.clickOnAreaJS(checkboxElement); + } catch (Exception e) { + e.printStackTrace(); + } + }, REGULAR_TEST_RUN_TIME); + SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog filtering time is " + + actualTestRunTime + " seconds"); + //Validate filtering results + CatalogVerificator.validateSubCategory("Generic", checkboxElementName); + } + + @Test(priority = 1) + public void lastUpdatedService() throws Exception { + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + List<WebElement> cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Expected : %s , Actual: %s", serviceMetadata.getName(), firstElementName), serviceMetadata.getName().equals(firstElementName)); + } + + @Test(priority = 17) + public void lastUpdatedResource() throws Exception { + // create resource + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + List<WebElement> cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Expected : %s , Actual: %s", vfMetaData.getName(), firstElementName), vfMetaData.getName().equals(firstElementName)); + } + + @Test(priority = 5) + public void fromCatalogCheckout() throws Exception { + // create resource + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + //Search in catalog + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + } + + @Test + public void keepSearchResultsInCatalogAfterBrowserBack() throws Exception { + ResourceReqDetails resourceMetadata = ElementFactory.getDefaultResource(); + ResourceUIUtils.createVF(resourceMetadata, getUser()); + ResourceGeneralPage.clickCheckinButton(resourceMetadata.getName()); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogSearchBox(resourceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(resourceMetadata.getName()); + + GeneralUIUtils.clickOnBrowserBackButton(); + + int numOfElementsInFilteredCatalog = CatalogVerificator.getNumberOfElementsFromCatalogHeader(); + assertTrue(String.format("Wrong number fo elements, Expected : %s , Actual: %s", 1, numOfElementsInFilteredCatalog), numOfElementsInFilteredCatalog == 1); + + List<WebElement> cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + String firstElementName = cardElements.get(0).getAttribute("textContent").trim(); + assertTrue(String.format("Wrong element name, Expected : %s , Actual: %s", resourceMetadata.getName(), firstElementName), resourceMetadata.getName().equals(firstElementName)); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Categories.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Categories.java new file mode 100644 index 0000000000..68f550cb44 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Categories.java @@ -0,0 +1,200 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.AdminGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.openecomp.sdc.be.model.category.SubCategoryDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.List; +import java.util.stream.Collectors; + +public class Categories extends SetupCDTest { + + + @Test + public void createResourceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + List<WebElement> resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + List<String> collect = resourceCategoriesList.stream().map(f -> f.getText()).collect(Collectors.toList()); + collect.contains(newResourceCategory); + + + } + + @Test + public void createServiceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List<WebElement> serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List<String> collect = serviceCategoriesList.stream().map(f -> f.getText()).collect(Collectors.toList()); + collect.contains(newserviceCategory); + + } + + + @Test + public void createResourceSubCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List<WebElement> serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List<WebElement> resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory, newSubCategory); + GeneralUIUtils.waitForLoader(); + } + + + @Test + public void createExistingResourceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + + } + + @Test + public void createExistingServiceCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.COMPONENT_CATEGORY_ALREADY_EXISTS.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + } + + @Test + public void createExsitingResourceSubCategory() throws Exception { + + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List<WebElement> serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List<WebElement> resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory, newSubCategory); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory, newSubCategory); + GeneralUIUtils.waitForLoader(); + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.COMPONENT_SUB_CATEGORY_EXISTS_FOR_CATEGORY.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + } + + + @Test + public void createServiceWithNewCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List<WebElement> serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List<WebElement> resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory, newSubCategory); + GeneralUIUtils.waitForLoader(); + AdminGeneralPage.selectUserManagmetTab(); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + List<CategoryDefinition> categories = serviceMetadata.getCategories(); + categories.get(0).setName(newserviceCategory); + + ServiceUIUtils.createService(serviceMetadata); + + } + + + @Test + public void createResourceWithNewCategory() throws Exception { + + AdminGeneralPage.selectCategoryManagmetTab(); + String newResourceCategory = ElementFactory.getDefaultCategory().getName(); + String newserviceCategory = ElementFactory.getDefaultCategory().getName(); + String newSubCategory = ElementFactory.getDefaultSubCategory().getName(); + AdminGeneralPage.createNewResourceCategory(newResourceCategory); + AdminGeneralPage.createNewServiceCategory(newserviceCategory); + List<WebElement> serviceCategoriesList = AdminGeneralPage.getServiceCategoriesList(); + List<WebElement> resourceCategoriesList = AdminGeneralPage.getResourceCategoriesList(); + AdminGeneralPage.addSubCategoryToResource(resourceCategoriesList, newResourceCategory, newSubCategory); + GeneralUIUtils.waitForLoader(); + AdminGeneralPage.selectUserManagmetTab(); + reloginWithNewRole(UserRoleEnum.DESIGNER); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + List<CategoryDefinition> categories = resourceMetaData.getCategories(); + CategoryDefinition categoryDefinition = categories.get(0); + categoryDefinition.setName(newResourceCategory); + SubCategoryDefinition subCategoryDefinition = categoryDefinition.getSubcategories().get(0); + subCategoryDefinition.setName(newSubCategory); + + ResourceUIUtils.createVF(resourceMetaData, getUser()); + + + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.ADMIN; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CustomizationUUID.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CustomizationUUID.java new file mode 100644 index 0000000000..e829a571c5 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/CustomizationUUID.java @@ -0,0 +1,331 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.frontend.ci.tests.verificator.CustomizationUUIDVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + +public class CustomizationUUID extends SetupCDTest { + + private static final String DESCRIPTION = "kuku"; + private static final String ARTIFACT_LABEL = "artifact3"; + private static final String ARTIFACT_LABEL_UPDATE = "artifactUpdate"; + private static final String GET_ARTIFACT_LIST_BY_CLASS_NAME = "i-sdc-designer-sidebar-section-content-item-artifact"; + private static final String HEAT_FILE_YAML_NAME = "Heat-File.yaml"; + private static final String HEAT_FILE_YAML_UPDATE_NAME = "Heat-File-Update.yaml"; + private String filePath; + + private CustomizationUUID() { + } + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath(""); + } + + @Test + public void uniqueCustomizationUUIDforeachVFi() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactCertifyState(); + + List customizationUUIDs = new ArrayList<String>(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement2 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement3 = addElemntToCanvas(vfMetaData, canvasManager); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement2); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement3); + + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement4 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement5 = addElemntToCanvas(vfMetaData, canvasManager); + CanvasElement VFiElement6 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement4); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement5); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement6); + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + + } + + + @Test + public void uniqueCustomizationUUIDafterArtifactCRUDofVFi() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactCertifyState(); + + List customizationUUIDs = new ArrayList<>(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, ArtifactTypeEnum.SNMP_POLL.getType()); + + canvasManager.clickOnCanvaElement(VFiElement1); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + canvasManager.clickOnCanvaElement(VFiElement1); + CompositionPage.showDeploymentArtifactTab(); + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ITEM.getValue() + ARTIFACT_LABEL); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to delete " + HEAT_FILE_YAML_NAME + " artifact" + " and check if deleted"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + ARTIFACT_LABEL); + GeneralPageElements.clickOKButton(); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + } + + + @Test + public void uniqueCustomizationUUIDchangeVFiVersion() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactCertifyState(); + + List customizationUUIDs = new ArrayList<>(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCertifyButton(vfMetaData.getName()); + + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + canvasManager.clickOnCanvaElement(VFiElement1); + CompositionPage.changeComponentVersion(canvasManager, VFiElement1, "2.0"); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + } + + + @Test + public void uniqueCustomizationUUIDaddRelation() throws Exception { + + + ResourceReqDetails vfMetaData = createNewResourceWithArtifactCertifyState(); + + List customizationUUIDs = new ArrayList<>(); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = addElemntToCanvas(vfMetaData, canvasManager); + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(vfMetaData.getName()); + + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + ServiceGeneralPage.clickCheckoutButton(); + canvasManager = CanvasManager.getCanvasManager(); + CanvasElement contrailPortElement = canvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.CONTRAIL_PORT); + canvasManager.linkElements(contrailPortElement, VFiElement1); + + canvasManager.clickOnCanvaElement(VFiElement1); + + + ServiceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + canvasManager = findServiceAndNavigateToCanvas(serviceMetadata); + addCanvasElementToList(customizationUUIDs, canvasManager, VFiElement1); + + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDs); + + } + + + public CanvasManager findServiceAndNavigateToCanvas(ServiceReqDetails serviceMetadata) throws Exception { + CanvasManager canvasManager; + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + canvasManager = CanvasManager.getCanvasManager(); + return canvasManager; + } + + public ResourceReqDetails createNewResourceWithArtifactCertifyState() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.clickEditArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.artifactPopup().insertDescription(newDescription); + DeploymentArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.searchForElement(NormativeTypesEnum.COMPUTE.name()); + CanvasManager canvasManagerVF = CanvasManager.getCanvasManager(); + CanvasElement VFiElement1 = canvasManagerVF.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(vfMetaData.getName()); + return vfMetaData; + } + + public void addCanvasElementToList(List customizationUUIDs, CanvasManager canvasManager, CanvasElement VFiElement1) + throws Exception { + canvasManager.clickOnCanvaElement(VFiElement1); + WebElement VFi1customizationUUID = CompositionPage.getCustomizationUUID(); + customizationUUIDs.add(VFi1customizationUUID.getText()); + } + + public CanvasElement addElemntToCanvas(ResourceReqDetails vfMetaData, CanvasManager canvasManager) + throws Exception { + CompositionPage.searchForElement(vfMetaData.getName()); + CanvasElement VFiElement1 = canvasManager.createElementOnCanvas(vfMetaData.getName()); + return VFiElement1; + } + + public static void changeDeleteAndValidateVersionOnGeneralPage(String previousVersion, String currentVersion, String serviceName) throws Exception { + GeneralPageElements.selectVersion("V" + previousVersion); + ServiceVerificator.verifyVersionUI(previousVersion); + GeneralUIUtils.clickJSOnElementByText("latest version"); + ServiceVerificator.verifyVersionUI(currentVersion); + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(serviceName); + ServiceVerificator.verifyVersionUI(previousVersion); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/DeploymentViewTests.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/DeploymentViewTests.java new file mode 100644 index 0000000000..f513a49fbf --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/DeploymentViewTests.java @@ -0,0 +1,290 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentPage; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.frontend.ci.tests.verificator.DeploymentViewVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.openqa.selenium.WebElement; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertTrue; + +public class DeploymentViewTests extends SetupCDTest { + + private static final int EXPECTED_NUMBER_OF_GROUPS = 3; + private String filePath; + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath(""); + } + + @DataProvider(name = "CSAR_VF_Files", parallel = false) + public Object[][] createDataX() { + return new Object[][]{{"vSeGWNew.csar"}, {"vSeGWNewDoubleMembers.csar"}, {"vSeGWNewSingleModule.csar"}}; + } + + + @Test(dataProvider = "CSAR_VF_Files") + public void deploymentScreenDCAEAssetImportCSARTest(String baseFileName) throws Exception { + // + setLog(baseFileName); +// getExtendTest().setDescription(baseFileName); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + List<WebElement> moduleRowsFromTable = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()); + DeploymentViewVerificator verificator = new DeploymentViewVerificator(filePath + baseFileName); + verificator.verifyDeploymentPageModules(moduleRowsFromTable); + for (WebElement moduleRow : moduleRowsFromTable) { + String moduleRowText = moduleRow.getText(); + verificator.verifyDeploymentPageSubElements(moduleRowText.split("\\.\\.")[1]); + DeploymentPage.updateModuleName(moduleRowText, "updatedName"); + String updatedModuleName = DeploymentPage.reconstructModuleName(moduleRowText.split("\\.\\."), "updatedName"); + verificator.verifyComponentNameChanged(moduleRowText, updatedModuleName); + // Close module + GeneralUIUtils.clickOnElementByText(updatedModuleName); + } + } + + @Test + public void deploymentScreenDCAEAssetUpdateWithNewGroupCSAR_TC1368223_Test() throws Exception { + String baseFileName = "baseUpdateMinusGroupFlowVF_NEW.csar"; + String updateFileName = "baseUpdateFlowVF_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", 2)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map<String, HashMap<String, String>> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + metaDataFromUI.put("base_ldsa", new HashMap<String, String>() { + { + put("version", "0"); + put("moduleID", "primary"); + } + }); + + // add new group, base_ldsa + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + @Test + public void deploymentScreenDCAEAssetDeleteGroupFromCSAR_TC1368281_Test() throws Exception { + String baseFileName = "baseUpdateFlowVF_NEW.csar"; + String updateFileName = "baseUpdateMinusGroupFlowVF_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map<String, HashMap<String, String>> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + // remove group base_ldsa + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group should be removed", 2)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + // validate that group was removed + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + + Map<String, HashMap<String, String>> metaDataFromUI2 = DeploymentPage.collectMetaDataFromUI(); + metaDataFromUI2.put("base_ldsa", new HashMap<String, String>() { + { + put("version", "0"); + put("moduleID", "primary"); + } + }); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // add group base_ldsa + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group should be added", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.updateVfWithCsar(filePath, baseFileName); + + // validate that group was added + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI2, new DeploymentViewVerificator(filePath + baseFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + @Test + public void deploymentScreenDCAEAssetUpdateWithNewGroupWithoutMembersCSAR_TC1368280_Test() throws Exception { + + String baseFileName = "baseUpdateMinusGroupFlowVF_NEW.csar"; + String updateFileName = "baseUpdateAddGroupNoMembersUpdateFlow_NEW.csar"; + String updateFileName2 = "baseUpdateFlowVF_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", 2)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + // add new group without members, base_ldsa + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group without members", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + Map<String, HashMap<String, String>> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + // validate that group was added and no members exist + DeploymentViewVerificator.regularDepoymentScreenVerificator(null, new DeploymentViewVerificator(filePath + updateFileName)); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // add group base_ldsa with members + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now, base_ldsa group with members", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName2); + + // validate that member was added to base_ldsa group + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName2)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + + @Test + public void deploymentScreenDCAEAssetImportCSARWithArtifactSection_TC1368282_1_Test() throws Exception { + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 4 artifacts in every group ", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(null, new DeploymentViewVerificator(filePath + baseFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + @Test + public void deploymentScreenDCAEAssetImportCSARRemoveArtifact_TC1368282_2_Test() throws Exception { + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup_NEW.csar"; + String updateFileName = "baseUpdateFlowOneArtifactToGroup_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 4 artifacts in every group ", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map<String, HashMap<String, String>> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // remove artifact from every group + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be 3 artifacts in every group")); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + @Test + public void deploymentScreenDCAEAssetImportCSARAddArtifact_TC1368282_3_Test() throws Exception { + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup_NEW.csar"; + String updateFileName = "baseUpdateFlowOneArtifactToGroup_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 3 artifacts in every group ", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, updateFileName, getUser()); + + Map<String, HashMap<String, String>> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + // add artifact to every group + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be 4 artifacts in every group")); + ResourceUIUtils.updateVfWithCsar(filePath, baseFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + baseFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + @Test + public void deploymentScreenDCAEAssetImportCSARMixArtifacts_TC1368282_4_Test() throws Exception { + String baseFileName = "baseUpdateFlowTwoArtifactsToGroup_NEW.csar"; + String updateFileName = "baseUpdateMixedArtifacts_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups, should be 4 artifacts in every group ", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); + + Map<String, HashMap<String, String>> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + //mix artifacts between groups + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, mixing between artifacts and groups", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator()); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + @Test + public void deploymentScreenDCAEAssetUpdateVFModule_TC1296437_Test() throws Exception { + String baseFileName = "baseUpdateMinusGroupFlowVF_NEW.csar"; + String updateFileName = "baseUpdateFlowVF_NEW.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating resource with %s groups ", 2)); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, baseFileName, getUser()); +// SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating %s group version, should be %s ", moduleRowText, metaDataFromUI.get(moduleRowText.split("\\.\\.")[1]))); + + Map<String, HashMap<String, String>> metaDataFromUI = DeploymentPage.collectMetaDataFromUI(); + metaDataFromUI.put("base_ldsa", new HashMap<String, String>() { + { + put("version", "0"); + put("moduleID", "primary"); + } + }); + + DeploymentViewVerificator.validateEditPopover(); + + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file, should be %s groups now", EXPECTED_NUMBER_OF_GROUPS)); + ResourceUIUtils.updateVfWithCsar(filePath, updateFileName); + + assertTrue(resourceMetaData.getName().equals(ResourceGeneralPage.getNameText())); + DeploymentViewVerificator.regularDepoymentScreenVerificator(metaDataFromUI, new DeploymentViewVerificator(filePath + updateFileName)); + DeploymentViewVerificator.validateModuleNameUpadate(); + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/GAB.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/GAB.java new file mode 100644 index 0000000000..c3f05a7d59 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/GAB.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 Nokia 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import java.util.Collections; +import java.util.List; + +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +public class GAB extends SetupCDTest { + + private static final int THREAD_SLEEP_TIME = 1000; + + private String pnfFilePath; + private String vnfFilePath; + + @BeforeClass + public void beforeClass() { + pnfFilePath = FileHandling.getFilePath("PNFs"); + vnfFilePath = FileHandling.getFilePath("VNFs"); + } + + @Test + public void addPmDictionaryDeploymentArtifactToPnfAndCheckMagnifierTest() throws Exception { + final int expectedHeaderSize = 10; + final int expectedRowSize = 3; + ResourceReqDetails pnfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.PNF, getUser()); + ResourceUIUtils.createPNF(pnfMetaData, getUser()); + GeneralPageElements.getLeftMenu().moveToDeploymentArtifactScreen(); + ArtifactInfo art1 = new ArtifactInfo(pnfFilePath, "pmDictionary.yml", "desc", "artifactpm", "PM_DICTIONARY"); + addArtifactAndOpenGAB(art1); + assertHeaderAndRowSize(expectedHeaderSize, expectedRowSize); + } + + @Test + public void addVesEventsDeploymentArtifactToVfAndCheckMagnifierTest() throws Exception { + final int expectedHeaderSize = 4; + final int expectedRowSize = 3; + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + GeneralPageElements.getLeftMenu().moveToDeploymentArtifactScreen(); + ArtifactInfo art1 = new ArtifactInfo(vnfFilePath, "vesEvent.yml", "desc", "artifactfault", "VES_EVENTS"); + addArtifactAndOpenGAB(art1); + assertHeaderAndRowSize(expectedHeaderSize, expectedRowSize); + } + + private void addArtifactAndOpenGAB(ArtifactInfo art1) throws Exception { + addNewArtifact(Collections.singletonList(art1)); + openGABPopup(art1); + } + + private void assertHeaderAndRowSize(final int expectedHeaderSize, final int expectedRowSize) { + final List<WebElement> headers = getListOfHeaders(); + AssertJUnit.assertEquals(expectedHeaderSize, headers.size()); + final List<WebElement> rows = getListOfRows(); + AssertJUnit.assertEquals(expectedRowSize, rows.size()); + } + + private List<WebElement> getListOfRows() { + return GeneralUIUtils.getWebElementsListBy(By.xpath("//sdc-modal//datatable-body//datatable-body-row")); + } + + private void openGABPopup(ArtifactInfo art1) throws InterruptedException { + SetupCDTest.getExtendTest() + .log(Status.INFO, String.format("Clicking on magnifier button %s", art1.getArtifactLabel())); + WebElement magnifierButtonElement = GeneralUIUtils.getWebElementByTestID( + DataTestIdEnum.ArtifactPageEnum.BROWSE_ARTIFACT.getValue() + art1.getArtifactLabel()); + SetupCDTest.getExtendTest() + .log(Status.INFO, String.format("Found magnifier button: %s", magnifierButtonElement.getText())); + magnifierButtonElement.click(); + Thread.sleep(THREAD_SLEEP_TIME); // have to wait until table will be rendered + } + + private List<WebElement> getListOfHeaders() { + return GeneralUIUtils.getWebElementsListBy(By.xpath("//sdc-modal//datatable-header//datatable-header-cell")); + } + + private void addNewArtifact(List<ArtifactInfo> deploymentArtifactList) throws Exception { + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + AssertJUnit.assertTrue(DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ImportDCAE.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ImportDCAE.java new file mode 100644 index 0000000000..5403e1312e --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ImportDCAE.java @@ -0,0 +1,679 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.InputsPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ToscaArtifactsPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.PropertiesUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.assertTrue; + +public class ImportDCAE extends SetupCDTest { + + private static final int CLICKING_ON_ELEMENT_TIMEOUT = 30; + + private static final String SERVICE_INPUT_TEST_VF2_CSAR = "service_input_test_VF2.csar"; + private String filePath; + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath(""); + } + + @Test + public void updateDCAEAsset() throws Exception { + ResourceReqDetails resourceMetaData = createDCAEAsset(); + + // update Resource + ResourceReqDetails updatedResource = new ResourceReqDetails(); + updatedResource.setName(ElementFactory.getResourcePrefix() + "UpdatedName" + resourceMetaData.getName()); + updatedResource.setDescription("kuku"); + updatedResource.setVendorName("updatedVendor"); + updatedResource.setVendorRelease("updatedRelease"); + updatedResource.setContactId("ab0001"); + updatedResource.setCategories(resourceMetaData.getCategories()); + updatedResource.setVersion("0.1"); + List<String> newTags = resourceMetaData.getTags(); + newTags.remove(resourceMetaData.getName()); + newTags.add(updatedResource.getName()); + updatedResource.setTags(newTags); + ResourceUIUtils.updateResource(updatedResource, getUser()); + + VfVerificator.verifyVFMetadataInUI(updatedResource); + VfVerificator.verifyVFUpdated(updatedResource, getUser()); + } + + @Test + public void vfcLinkedToComputeInDCAEAssetFlowTest() throws Exception { + final int expectedNumberOfComponentInstances = 4; + String fileName = "importVFC_VFC14.yml"; + ResourceReqDetails atomicResourceMetaData = + ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory( + ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try { + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(atomicResourceMetaData.getName()); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + TesterOperationPage.certifyComponent(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + ResourceReqDetails resourceMetaData = createDCAEAsset(); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = canvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement cpElement = canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + Assert.assertNotNull(cpElement); + ServiceVerificator.verifyNumOfComponentInstances( + resourceMetaData, "0.1", + expectedNumberOfComponentInstances, getUser()); + + canvasManager.linkElements(cpElement, computeElement); + + resourceMetaData.setVersion("0.1"); + VfVerificator.verifyLinkCreated(resourceMetaData, getUser(), 1); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + @Test + public void addUpdateDeleteDeploymentArtifactToDCAEAssetTest() throws Exception { + createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType())); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", ArtifactTypeEnum.YANG_XML.getType())); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.clickEditArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.artifactPopup().insertDescription(newDescription); + DeploymentArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + assertTrue("artifact " + deploymentArtifactList.get(0).getArtifactLabel() + "is not deleted", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size() - 1)); + + assertTrue("artifact " + deploymentArtifactList.get(1).getArtifactLabel() + "is not displayed", DeploymentArtifactPage.clickOnArtifactDescription(deploymentArtifactList.get(1).getArtifactLabel()).isDisplayed()); + } + + @Test + public void addUpdateDeleteInformationalArtifactDCAEAssetTest() throws Exception { + createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType()); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + assertTrue("artifact table does not contain artifacts uploaded", InformationalArtifactPage.checkElementsCountInTable(1)); + + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifact.getArtifactLabel()); + assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + assertTrue("artifact " + informationalArtifact.getArtifactLabel() + "is not deleted", InformationalArtifactPage.checkElementsCountInTable(0)); + } + + @Test + public void addPropertiesToVfcInstanceInDCAEAssetTest() throws Exception { + + if (true) { +// throw new SkipException("Open bug 373762, can't update properties on CP or VFC instance on Composition screen"); + SetupCDTest.getExtendTest().log(Status.INFO, "Open bug 373762, can't update properties on CP or VFC instance on Composition screen"); + } + + String fileName = "importVFC_VFC15.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try { + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + vfCanvasManager.clickOnCanvaElement(vfcElement); + CompositionPage.showPropertiesAndAttributesTab(); + List<WebElement> properties = CompositionPage.getProperties(); + String propertyValue = "abc123"; + for (int i = 0; i < 2; i++) { + WebElement findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label")); + findElement.click(); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue); + PropertiesPage.getPropertyPopup().clickSave(); + + findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-value")); + assertTrue(findElement.getText().equals(propertyValue)); + } + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void changeInstanceVersionDCAEAssetTest() throws Exception { + ResourceReqDetails atomicResourceMetaData = null; + ResourceReqDetails vfMetaData = null; + CanvasManager vfCanvasManager; + CanvasElement vfcElement = null; + String fileName = "importVFC_VFC16.yml"; + try { + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + //TODO Andrey changed to click on checkIn button + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + vfMetaData = createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + //TODO Andrey should click on certify button + CompositionPage.clickCertifyButton(vfMetaData.getName()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + GeneralUIUtils.closeErrorMessage(); + GeneralPageElements.clickOnHomeButton(); + + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + ResourceGeneralPage.clickCertifyButton(atomicResourceMetaData.getName()); + + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfMetaData.setVersion("0.2"); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "1.0"); + + //verfication + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "1.0"); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + // future removed from ui + @Test(enabled = true) + public void addUpdateDeleteSimplePropertiesToDCAEAssetTest() throws Exception { + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + List<PropertyTypeEnum> propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = PropertiesPage.getElemenetsFromTable().size(); + for (PropertyTypeEnum prop : propertyList) { + PropertiesUIUtils.addNewProperty(prop); + } + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> PropertiesPage.getElemenetsFromTable())); + VfVerificator.verifyPropertiesInUI(propertyList); + PropertiesPage.verifyTotalProperitesField(propertiesCount + propertyList.size()); + + PropertyTypeEnum prop = propertyList.get(0); + prop.setDescription("updatedDescription"); + prop.setValue("value"); + PropertiesUIUtils.updateProperty(prop); + + PropertiesPage.clickDeletePropertyArtifact(prop.getName()); + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size() - 1, () -> PropertiesPage.getElemenetsFromTable())); + } + + // future removed from ui + @Test(enabled = true) + public void DCAEAssetInstancesInputScreenTest() throws Exception { + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + + Map<String, String> elementsIntancesMap = new HashMap<String, String>(); + for (DataTestIdEnum.LeftPanelCanvasItems element : Arrays.asList(DataTestIdEnum.LeftPanelCanvasItems.DATABASE)) { + CanvasElement elementOnCanvas = vfCanvasManager.createElementOnCanvas(element); + vfCanvasManager.clickOnCanvaElement(elementOnCanvas); + String selectedInstanceName = CompositionPage.getSelectedInstanceName(); + elementsIntancesMap.put(selectedInstanceName, element.getValue()); + } + + CompositionPage.moveToInputsScreen(); + int canvasElementsSize = vfCanvasManager.getCanvasElements().size() + 2; + List<String> inputsNamesFromTable = InputsPage.getVFCInstancesNamesFromTable(); + assertTrue(String.format("Instances count is not as Expected: %s Actual: %s", canvasElementsSize, inputsNamesFromTable.size()), inputsNamesFromTable.size() == canvasElementsSize); + + for (String instanceName : inputsNamesFromTable) { + String resourceName = instanceName.split(" ")[0]; + ResourceReqDetails resource = new ResourceReqDetails(); + resource.setName(resourceName); + resource.setVersion("1.0"); + if (resourceName.equals("Port")) { + resource.setResourceType(ResourceTypeEnum.CP.toString()); + } else { + resource.setResourceType(ResourceTypeEnum.VFC.toString()); + } + RestResponse restResponse = RestCDUtils.getResource(resource, getUser()); + Map<String, String> propertiesNameTypeJson = ResponseParser.getPropertiesNameType(restResponse); + + List<WebElement> propertyRowsFromTable = InputsPage.getInstancePropertiesList(resourceName); + assertTrue("Some properties are missing in table. Instance name is : " + resourceName, propertyRowsFromTable.size() == propertiesNameTypeJson.size()); + VfVerificator.verifyVfInputs(instanceName, propertiesNameTypeJson, propertyRowsFromTable); + + GeneralUIUtils.clickOnElementByText(resourceName); + } + } + + @Test + public void addAllInformationalArtifactPlaceholdersInDCAEAssetTest() throws Exception { + createDCAEAsset(); + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + int fileNameCounter = 0; + String fileName; + for (DataTestIdEnum.InformationalArtifactsPlaceholders informArtifact : DataTestIdEnum.InformationalArtifactsPlaceholders.values()) { + fileName = HEAT_FILE_YAML_NAME_PREFIX + fileNameCounter + HEAT_FILE_YAML_NAME_SUFFIX; + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(informArtifact, + FileHandling.getFilePath("uniqueFileNames"), fileName, informArtifact.getValue()); + fileNameCounter++; + } + + assertThat(InformationalArtifactPage.checkElementsCountInTable(DataTestIdEnum.InformationalArtifactsPlaceholders.values().length)).isTrue(); + } + + @Test + public void verifyToscaArtifactsExistDCAEAssetTest() throws Exception { + ResourceReqDetails vfMetaData = createDCAEAsset(); + + final int numOfToscaArtifacts = 2; + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); + + for (int i = 0; i < numOfToscaArtifacts; i++) { + String typeFromScreen = ToscaArtifactsPage.getArtifactType(i); + assertTrue(typeFromScreen.equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) || typeFromScreen.equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())); + } + //TODO Andrey should click on certify button + ToscaArtifactsPage.clickCertifyButton(vfMetaData.getName()); + vfMetaData.setVersion("1.0"); + VfVerificator.verifyToscaArtifactsInfo(vfMetaData, getUser()); + } + + @Test + public void DCAEAssetCertificationTest() throws Exception { + ResourceReqDetails vfMetaData = createDCAEAsset(); + + String vfName = vfMetaData.getName(); + + ResourceGeneralPage.clickCheckinButton(vfName); + GeneralUIUtils.findComponentAndClick(vfName); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(vfName); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfName); + TesterOperationPage.certifyComponent(vfName);*/ + + vfMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + /*reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + GeneralUIUtils.findComponentAndClick(vfName); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void deleteDCAEAssetCheckedoutTest() throws Exception { + ResourceReqDetails vfMetaData = createDCAEAsset(); + + GeneralPageElements.clickTrashButtonAndConfirm(); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyVfDeleted(vfMetaData, getUser()); + } + + @Test + public void revertDCAEAssetMetadataTest() throws Exception { + ResourceReqDetails vfMetaData = createDCAEAsset(); + + ResourceReqDetails vfRevertDetails = new ResourceReqDetails(); + vfRevertDetails.setName("ciUpdatedName"); + vfRevertDetails.setDescription("kuku"); + vfRevertDetails.setCategories(vfMetaData.getCategories()); + vfRevertDetails.setVendorName("updatedVendor"); + vfRevertDetails.setVendorRelease("updatedRelease"); + ResourceUIUtils.fillResourceGeneralInformationPage(vfRevertDetails, getUser(), false); + + GeneralPageElements.clickRevertButton(); + + VfVerificator.verifyVFMetadataInUI(vfMetaData); + } + + @Test + public void addDeploymentArtifactInCompositionScreenDCAEAssetTest() throws Exception { + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3", ArtifactTypeEnum.OTHER.getType()); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className("i-sdc-designer-sidebar-section-content-item-artifact")); + Assert.assertEquals(1, actualArtifactList.size()); + } + + // future removed from ui + @Test(enabled = true) + public void addPropertyInCompositionScreenDCAEAssetTest() throws Exception { + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showPropertiesAndAttributesTab(); + List<PropertyTypeEnum> propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = CompositionPage.getProperties().size(); + for (PropertyTypeEnum prop : propertyList) { + PropertiesUIUtils.addNewProperty(prop); + } + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> CompositionPage.getProperties())); + } + + @Test + public void addDeploymentArtifactAndVerifyInCompositionScreenDCAEAssetTest() throws Exception { + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + ArtifactInfo deploymentArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType()); + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + assertTrue(DeploymentArtifactPage.checkElementsCountInTable(1)); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showDeploymentArtifactTab(); + List<WebElement> deploymentArtifactsFromScreen = CompositionPage.getDeploymentArtifacts(); + assertTrue(1 == deploymentArtifactsFromScreen.size()); + + String actualArtifactFileName = deploymentArtifactsFromScreen.get(0).getText(); + assertTrue("asc_heat-0-2.yaml".equals(actualArtifactFileName)); + } + + @Test + public void checkoutDCAEAssetTest() throws Exception { + ResourceReqDetails vfMetaData = createDCAEAsset(); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + + vfMetaData.setVersion("0.2"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(vfMetaData.getName()); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + vfMetaData.setVersion("1.1"); + vfMetaData.setUniqueId(null); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + } + + @Test + public void deleteInstanceFromDCAEAssetCanvas() throws Exception { + ResourceReqDetails vfMetaData = createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = CompositionPage.addElementToCanvasScreen(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE, vfCanvasManager); + + vfCanvasManager.clickOnCanvaElement(computeElement); + vfCanvasManager.deleteElementFromCanvas(computeElement); + + VfVerificator.verifyNumOfComponentInstances(vfMetaData, 2, getUser()); + } + + @Test + public void changeInstanceNameInDCAEAssetTest() throws Exception { + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = CompositionPage.addElementToCanvasScreen(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE, vfCanvasManager); + + String updatedInstanceName = "updatedName"; + vfCanvasManager.updateElementNameInCanvas(computeElement, updatedInstanceName); + + String actualSelectedInstanceName = CompositionPage.getSelectedInstanceName(); + assertTrue(updatedInstanceName.equals(actualSelectedInstanceName)); + } + + @Test + public void submitDCAEAssetForTestingWithNonCertifiedAsset() throws Exception { + String fileName = "importVFC_VFC17.yml"; + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + //TODO Andrey changed to click on checkIn button + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ResourceReqDetails vfMetaData = createDCAEAsset(); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.addElementToCanvasScreen(atomicResourceMetaData.getName(), canvasManager); + + try { + //TODO Andrey should click on certify button + CompositionPage.clickCertifyButton(vfMetaData.getName()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void isDisabledAndReadOnlyInCheckinDCAEAssetTest() throws Exception { + ResourceReqDetails vfMetaData = createDCAEAsset(); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + DataTestIdEnum.ResourceMetadataEnum[] fieldsForCheck = {DataTestIdEnum.ResourceMetadataEnum.RESOURCE_NAME, + DataTestIdEnum.ResourceMetadataEnum.DESCRIPTION, + DataTestIdEnum.ResourceMetadataEnum.VENDOR_NAME, + DataTestIdEnum.ResourceMetadataEnum.VENDOR_RELEASE, + DataTestIdEnum.ResourceMetadataEnum.CONTACT_ID, + DataTestIdEnum.ResourceMetadataEnum.CATEGORY, + DataTestIdEnum.ResourceMetadataEnum.TAGS}; + + for (DataTestIdEnum.ResourceMetadataEnum field : fieldsForCheck) { + VfVerificator.verifyIsElementDisabled(field.getValue(), field.name()); + } + VfVerificator.verifyIsElementDisabled(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue(), DataTestIdEnum.LifeCyleChangeButtons.CREATE.name()); + } + + @Test + public void removeFileFromGeneralPageDCAEAssetTest() throws Exception { + String fileName2 = SERVICE_INPUT_TEST_VF2_CSAR; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsarNoCreate(resourceMetaData, filePath, fileName2, getUser()); + GeneralPageElements.clickDeleteFile(); + + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue(), CLICKING_ON_ELEMENT_TIMEOUT); + assert (false); + } catch (Exception e) { + assert (true); + } + } + + @Test + public void activityLogDCAEAssetTest() throws Exception { + createDCAEAsset(); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", ArtifactTypeEnum.OTHER.getType()); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + ResourceGeneralPage.getLeftMenu().moveToActivityLogScreen(); + + int numberOfRows = GeneralUIUtils.getElementsByCSS("div[class^='flex-container']").size(); + assertTrue("Wrong rows number, should be 2", numberOfRows == 2); + } + + @Test + public void checkinCheckoutChangeDeleteVersionDCAEAssetTest() throws Exception { + ResourceReqDetails atomicResourceMetaData = createDCAEAsset(); + + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + GeneralPageElements.selectVersion("V0.1"); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKIN); + GeneralUIUtils.clickJSOnElementByText("latest version"); + + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()).getText(); + assertTrue("Expected version: V0.1, Actual version: " + actualVersion, actualVersion.equals("V0.1")); + } + + @Test + public void badFileDCAEAssetTest() throws Exception { + String customFileName = "badVF.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + try { + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, customFileName, getUser()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.CSAR_INVALID.name()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating error messdge...")); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + } + + @Test + public void validContactAfterCreateDCAEAssetTest() throws Exception { + ResourceReqDetails resourceMetaData = createDCAEAsset(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating that userID equal to user that was logged in...")); + assertTrue("Wrong userId", resourceMetaData.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + public ResourceReqDetails createDCAEAsset() throws Exception { + String fileName2 = SERVICE_INPUT_TEST_VF2_CSAR; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + resourceMetaData.setVersion("0.1"); + return resourceMetaData; + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ImportVFCAsset.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ImportVFCAsset.java new file mode 100644 index 0000000000..a703e6d46b --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ImportVFCAsset.java @@ -0,0 +1,370 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.onap.sdc.frontend.ci.tests.verificator.PropertyVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.UploadArtifactPopup; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.PropertiesUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.assertTrue; + +@Test(singleThreaded = true) +public class ImportVFCAsset extends SetupCDTest { + + private static final int CLICKING_ON_ELEMENT_TIMEOUT = 30; + private ResourceReqDetails atomicResourceMetaData; + private String filePath; + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath(""); + } + + @DataProvider(name = "assetFiles", parallel = false) + public Object[][] createDataX() { + return new Object[][]{{"importVFC_VFC9.yml"}, {"CP.yml"}, {"VL.yml"}}; + } + + @Test + public void importVFCTest() throws Exception { + String fileName = "importVFC_VFC1.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + } + + @Test + public void importDuplicateVFCTest() throws Exception { + String fileName = "importVFC_VFC2.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ResourceReqDetails atomicResourceMetaDataDup = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_INFRASTRUCTURE, getUser()); + try { + ResourceUIUtils.importVfc(atomicResourceMetaDataDup, filePath, fileName, getUser()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.RESOURCE_ALREADY_EXISTS.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + } + + @Test + public void badFileVFCTest() throws Exception { + String fileName = "importVFC_VFC3.yml"; + String customFileName = "Heat-File 1.yaml"; + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + try { + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, customFileName, getUser()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.INVALID_TOSCA_TEMPLATE.name()); + Assert.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + } + + @Test + public void validContactAfterCreateVFCTest() throws Exception { + String fileName = "importVFC_VFC4.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + assertTrue("wrong userId", atomicResourceMetaData.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + @Test + public void validContactAfterUpdateVFCTest() throws Exception { + String fileName = "importVFC_VFC5.yml"; + String userIdUpdated = "up1234"; + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceUIUtils.defineUserId(userIdUpdated); + assertTrue("userId is not updated", userIdUpdated.equals(ResourceGeneralPage.getContactIdText())); + } + + @Test + public void addUpdateDeleteDeploymentArtifactToVFCTest() throws Exception { + String fileName = "importVFC_VFC6.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<ArtifactInfo>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact, new UploadArtifactPopup(true)); + } + assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.updateDescription(newDescription, deploymentArtifactList.get(0)); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + assertTrue("artifact " + deploymentArtifactList.get(0).getArtifactLabel() + "is not deleted", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size() - 1)); + + assertTrue("artifact " + deploymentArtifactList.get(1).getArtifactLabel() + "is not displayed", DeploymentArtifactPage.clickOnArtifactDescription(deploymentArtifactList.get(1).getArtifactLabel()).isDisplayed()); + } + + @Test + public void addUpdateDeletePlaceholdersInformationalArtifactVFCTest() throws Exception { + String fileName = "importVFC_VFC7.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + // create artifacts + List<ArtifactInfo> informationalArtifactList = new ArrayList<ArtifactInfo>(); + informationalArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + informationalArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuuuuku", "artifact3", "HEAT")); + for (ArtifactInfo informationalArtifact : informationalArtifactList) { + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + } + assertThat(InformationalArtifactPage.checkElementsCountInTable(informationalArtifactList.size())). + as("Check that artifact table contains artifacts uploaded").isTrue(); + + // update artifact description + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifactList.get(0).getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifactList.get(0).getArtifactLabel()); + assertThat(actualArtifactDescription).as("Check artifact description update").isEqualTo(newDescription); + + // delete artifacts + for (ArtifactInfo informationalArtifact : informationalArtifactList) { + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + } + + assertThat(InformationalArtifactPage.checkElementsCountInTable(0)). + as("Check that all artifacts were deleted").isTrue(); + + // fill placeholders + int fileNameCounter = 0; + for (DataTestIdEnum.InformationalArtifactsPlaceholders informArtifact : DataTestIdEnum.InformationalArtifactsPlaceholders.values()) { + fileName = HEAT_FILE_YAML_NAME_PREFIX + fileNameCounter + HEAT_FILE_YAML_NAME_SUFFIX; + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(informArtifact, FileHandling.getFilePath("uniqueFileNames"), + fileName, informArtifact.getValue()); + fileNameCounter++; + } + assertThat(InformationalArtifactPage.checkElementsCountInTable(DataTestIdEnum.InformationalArtifactsPlaceholders.values().length)).isTrue(); + } + + @Test + public void addSimplePropertiesToVFCTest() throws Exception { + String fileName = "importVFC_VFC8.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + List<PropertyTypeEnum> propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER, PropertyTypeEnum.FLOAT); + int propertiesCount = PropertiesPage.getElemenetsFromTable().size(); + for (PropertyTypeEnum prop : propertyList) { + PropertiesUIUtils.addNewProperty(prop); + } + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> PropertiesPage.getElemenetsFromTable())); + + } + + @Test + public void updateAfterCheckoutNewSimplePropertiesVFCTest() throws Exception { + String fileName = "importVFC_VFC16.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + List<PropertyTypeEnum> propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER, PropertyTypeEnum.FLOAT); + int propertiesCount = PropertiesPage.getElemenetsFromTable().size(); + for (PropertyTypeEnum prop : propertyList) { + PropertiesUIUtils.addNewProperty(prop); + } + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + + for (PropertyTypeEnum prop : propertyList) { + PropertiesUIUtils.updateProperty(prop); + } + assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> PropertiesPage.getElemenetsFromTable())); + + for (PropertyTypeEnum prop : propertyList) { + PropertiesPage.clickOnProperty(prop.getName()); + PropertyVerificator.validateEditVFCPropertiesPopoverFields(prop); + PropertiesPage.getPropertyPopup().clickCancel(); + } + + } + + + @Test(dataProvider = "assetFiles") + public void checkinCheckoutChangeDeleteVersionVFCTest(String customfileName) throws Exception { + setLog(customfileName); + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, customfileName, getUser()); + + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + GeneralPageElements.selectVersion("V0.1"); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKIN); + GeneralUIUtils.clickJSOnElementByText("latest version"); + + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()).getText(); + assertTrue("Expected version: V0.1, Actual version: " + actualVersion, actualVersion.equals("V0.1")); + } + + @Test + public void certificationVFCTest() throws Exception { + String fileName = "importVFC_VFC10.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + String vfName = atomicResourceMetaData.getName(); + + ResourceGeneralPage.clickCheckinButton(vfName); + GeneralUIUtils.findComponentAndClick(vfName); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(vfName); + + atomicResourceMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(atomicResourceMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + GeneralUIUtils.findComponentAndClick(vfName); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void activityLogVFCTest() throws Exception { + String fileName = "importVFC_VFC11.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + ResourceGeneralPage.getLeftMenu().moveToActivityLogScreen(); + + int numberOfRows = GeneralUIUtils.getElementsByCSS("div[class^='flex-container']").size(); + assertTrue("Wrong rows number, should be 2", numberOfRows == 2); + } + + @Test + public void removeFileFromGeneralPageVFCTest() throws Exception { + String fileName = "importVFC_VFC12.yml"; + + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfcNoCreate(atomicResourceMetaData, filePath, fileName, getUser()); + + GeneralPageElements.clickDeleteFile(); + + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue(), CLICKING_ON_ELEMENT_TIMEOUT); + assert (false); + } catch (Exception e) { + assert (true); + } + } + + @Test + public void maxLengthGeneralInformationVFCTest() throws Exception { + String fileName = "importVFC_VFC13.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceUIUtils.fillMaxValueResourceGeneralInformationPage(atomicResourceMetaData); + assertTrue(GeneralUIUtils.checkForDisabledAttribute(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue())); + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardViaApis.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardViaApis.java new file mode 100644 index 0000000000..0bc57934ca --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardViaApis.java @@ -0,0 +1,142 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import fj.data.Either; +import org.onap.sdc.frontend.ci.tests.dataProvider.OnbordingDataProviders; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +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.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.slf4j.LoggerFactory; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.sql.Timestamp; +import java.util.List; + +import static org.testng.AssertJUnit.assertTrue; + + +public class OnboardViaApis { + + + private static final String FULL_PATH = "C://tmp//CSARs//"; + protected static String filepath = FileHandling.getVnfRepositoryPath(); + + //------------------------------------------------------------------------------------------------------- + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + // ResourceReqDetails resourceDetails; + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + + + @BeforeMethod + public void before() { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.getLogger("org.apache").setLevel(Level.OFF); + lc.getLogger("org.*").setLevel(Level.OFF); + lc.getLogger("org.openecomp.sdc.ci.tests.datatypes.http.HttpRequest").setLevel(Level.OFF); + } + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "randomVNF_List") + public void onboardVNFTestViaApis(String filepath, String vnfFile) throws Exception, Throwable { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); //getServiceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + Service service = runOnboardViaApisOnly(serviceReqDetails, resourceReqDetails, filepath, vnfFile); + } + + + @Test + public void onboardingAndParser() throws Exception { + final int fileFromFolderToGet =7; + Service service = null; + List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filepath); + String vnfFile = fileNamesFromFolder.get(fileFromFolderToGet); + System.err.println(timestamp + " Starting test with VNF: " + vnfFile); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); //getServiceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + service = runOnboardViaApisOnly(serviceReqDetails, resourceReqDetails, filepath, vnfFile); + } + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "randomVNF_List") + public void updateVSPFullScenario(String filepath, String vnfFile) throws Exception { + //CREATE DATA REQUIRED FOR TEST + boolean skipReport = true; + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, sdncDesignerDetails1, + vendorLicenseModel); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); //getServiceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstanceDefinition = addComponentInstanceToComponentContainer.left().value(); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + // TEST START + + VendorLicenseModelRestUtils.updateVendorLicense(vendorLicenseModel, sdncDesignerDetails1, false); + VendorLicenseModelRestUtils.validateVlmExist(vendorLicenseModel.getVendorId(), vendorLicenseModel.getVersion(), sdncDesignerDetails1); + + // Update the VSP With the VLM new version and submit the VSP + vendorSoftwareProductObject = VendorSoftwareProductRestUtils.updateVSPWithNewVLMParameters(vendorSoftwareProductObject, + vendorLicenseModel, sdncDesignerDetails1); + VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1); + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + System.out.println(distributeAndValidateService); + } + + public Service runOnboardViaApisOnly(ServiceReqDetails serviceReqDetails, ResourceReqDetails resourceReqDetails, String filepath, String vnfFile) throws Exception { + + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUtillViaApis.createVspViaApis(resourceReqDetails, filepath, vnfFile, sdncDesignerDetails1); + vendorSoftwareProductObject.setName(vendorSoftwareProductObject.getName()); + + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstanceDefinition = addComponentInstanceToComponentContainer.left().value(); + + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + return service; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java new file mode 100644 index 0000000000..4cec05ef9c --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardingFlowsThroughAPI.java @@ -0,0 +1,500 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.onap.sdc.backend.ci.tests.data.providers.OnboardingDataProviders; +import org.onap.sdc.frontend.ci.tests.dataProvider.OnbordingDataProviders; +import org.onap.sdc.backend.ci.tests.datatypes.enums.CvfcTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.frontend.ci.tests.verificator.CatalogVerificator; +import org.openecomp.sdc.be.model.ArtifactDefinition; +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.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.FileHandling; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.testng.AssertJUnit.assertTrue; + +public class OnboardingFlowsThroughAPI extends SetupCDTest { + + protected boolean skipReport = false; + private User sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + +// https://sdp.web.att.com/fa3qm1/web/console/Application_Development_Tools_QM_20.20.01#action=com.ibm.rqm.planning.home.actionDispatcher&subAction=viewTestPlan&id=6184 + + @Test + public void addVesFileToVsp() throws Exception { + String vnfFile = "vMME_Ericsson_small_v2.zip"; + String vesArtifactFile = "VES.zip"; + String filePath = FileHandling.getFilePath("VFCArtifacts"); + String vesArtifactFileLocation = filePath + File.separator + vesArtifactFile; + List<String> vesArtifacts = FileHandling.getFileNamesFromZip(vesArtifactFileLocation); + List<String> tempVesArtifacts = FileHandling.getFileNamesFromZip(vesArtifactFileLocation); + Map<CvfcTypeEnum, String> cvfcArtifacts = new HashMap<>(); + cvfcArtifacts.put(CvfcTypeEnum.VES_EVENTS, vesArtifactFileLocation); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, cvfcArtifacts); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + List<ComponentInstance> componentInstances = resource.getComponentInstances(); + for (ComponentInstance componentInstance : componentInstances) { + if (componentInstance.getDeploymentArtifacts() != null && !componentInstance.getDeploymentArtifacts().isEmpty()) { + Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts(); + for (Entry<String, ArtifactDefinition> entry : deploymentArtifacts.entrySet()) { + if (entry.getValue().getArtifactType().equals(CvfcTypeEnum.VES_EVENTS.getValue())) { + for (String vesArtifact : vesArtifacts) { + if (entry.getValue().getArtifactName().equals(vesArtifact)) { + tempVesArtifacts.remove(vesArtifact); + } + } + } + } + } + } + assertTrue("Not all VES_EVENTS artifact files are on the resource instance", tempVesArtifacts.isEmpty()); + } + +// 741433: Update Old VSP +// 2. Updated VSP "JSA AUG 2017" with the attached zip from v3 to v4. Follow normal steps to update the VF +// 3. Update the VSP "vHSS-EPC-RDM3-Lab-0830" using the attached zip. Follow the normal steps to update the VF +// @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "randomVNF_List") +// public void create2(String filePath, String vnfFile) throws Exception{ +// setLog(vnfFile); +// } + + + // 741509: E2E flow using old VLM + @Test + public void VlmReuse() throws Exception { + List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List<String> newRandomFileNamesFromFolder = OnboardingDataProviders.getRandomElements(2, fileNamesFromFolder); + String filePath = FileHandling.getVnfRepositoryPath(); + String vnfFile = newRandomFileNamesFromFolder.get(0); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); +// setLog(vnfFile); + getExtendTest().log(Status.INFO, "Create Vendor License"); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + getExtendTest().log(Status.INFO, "Create Vendor Software Product: " + resourceReqDetails.getName()); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + getExtendTest().log(Status.INFO, "Create Resource: " + resourceReqDetails.getName()); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + getExtendTest().log(Status.INFO, "Certify the Resource: " + resourceReqDetails.getName()); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + getExtendTest().log(Status.INFO, "Add VF to service"); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, "Certify the service"); + service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, "Start distributing the service"); + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, "Service distributed"); + assertTrue("Distribution of service " + service.getName() + " failed", distributeAndValidateService); + +// update + vnfFile = newRandomFileNamesFromFolder.get(1); + getExtendTest().log(Status.INFO, "Going to update VLM with new file " + vnfFile); + VendorLicenseModelRestUtils.updateVendorLicense(vendorLicenseModel, sdncDesignerDetails, false); + vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + getExtendTest().log(Status.INFO, "Create new VSP: " + vendorSoftwareProductObject.getName()); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + getExtendTest().log(Status.INFO, "Create new resource: " + resourceReqDetails.getName()); + resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + getExtendTest().log(Status.INFO, "Certify the resource"); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create new service: " + serviceReqDetails.getName()); + service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + getExtendTest().log(Status.INFO, "Add VF to service"); + addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, "Certify the service"); + service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, "Start distributing the service"); + distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, "Service distributed"); + assertTrue("Distribution of service " + service.getName() + " failed", distributeAndValidateService); + } + + + // 741607: E2E flow using old VSP + @Test + public void updateVfiVersionOnServiceLevel() throws Throwable { + List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List<String> newRandomFileNamesFromFolder = OnboardingDataProviders.getRandomElements(2, fileNamesFromFolder); + String filePath = FileHandling.getVnfRepositoryPath(); + String vnfFile = newRandomFileNamesFromFolder.get(0); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + assertTrue("Distribution of service " + service.getName() + " failed", distributeAndValidateService); + +// update resource to v2.0 + String updateVnfFile = newRandomFileNamesFromFolder.get(1); + getExtendTest().log(Status.INFO, "Going to update VNF with file " + vnfFile); + VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails, filePath, updateVnfFile); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resourceReqDetails.setUniqueId(resource.getUniqueId()); + resourceReqDetails.setVersion(resource.getVersion()); + resource = AtomicOperationUtils.updateResource(resourceReqDetails, sdncDesignerDetails, true).left().value(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + assertTrue("Distribution of service " + service.getName() + " failed", distributeAndValidateService); + } + + +// 741608: E2E flow using old Service +// @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "randomVNF_List") +// public void create5(String filePath, String vnfFile) throws Exception{ +// setLog(vnfFile); +// // 1. Create Service with old resource -> Certify this Service - > Distribute +// // 2. Service is distributed +// // 3. Update old Service: fetch few new resources and few old resources -> Certify this Service - > Distribute +// // 4. Service is distributed +// } + + // 741633: Update HEAT parameter value + @Test() + public void updateHeatParametersValue() throws Throwable { + String msg = "VfArtifacts-->checkDefaultCreatedEnvArtifactsAfterVspUpdate tests with data provider index 4(last one) check it fully"; + getExtendTest().log(Status.INFO, msg); + } + + // temporaly disabled, until fixed + @Test() + public void updateVSPNameTest() throws Throwable { + // External Defect: 430425 +// Import VSP v1.0 + List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List<String> newRandomFileNamesFromFolder = OnboardingDataProviders.getRandomElements(1, fileNamesFromFolder); + String filePath = FileHandling.getVnfRepositoryPath(); + String vnfFile = newRandomFileNamesFromFolder.get(0); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); + getExtendTest().log(Status.INFO, "Create Vendor License Model " + vendorLicenseModel.getVendorLicenseName()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + getExtendTest().log(Status.INFO, "Create Vendor Software Product " + resourceReqDetails.getName()); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + +// Create VF, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + getExtendTest().log(Status.INFO, "Create VF " + resourceReqDetails.getName()); + Resource resource_v1 = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + getExtendTest().log(Status.INFO, "Certify VF " + resourceReqDetails.getName()); + AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + +// Update VSP to v2.0 wih the zip from v1.0, update VSP name + getExtendTest().log(Status.INFO, "Update VSP to version 2.0"); + String origVspName = vendorSoftwareProductObject.getName(); + vendorSoftwareProductObject.setName("Upd" + ElementFactory.generateUUIDforSufix()); + vendorSoftwareProductObject = VendorSoftwareProductRestUtils.updateVSPWithNewVLMParameters(vendorSoftwareProductObject, + vendorLicenseModel, sdncDesignerDetails1); + VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1); + + //Validate that VF cannot be found by the updated VSP name + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogSearchBox(vendorSoftwareProductObject.getName()); + int numOfElementsInFilteredCatalog = CatalogVerificator.getNumberOfElementsFromCatalogHeader(); + assertTrue(String.format("Wrong number fo elements, Expected : %s , Actual: %s", 0, numOfElementsInFilteredCatalog), numOfElementsInFilteredCatalog == 0); + + //Update VF with the new VSP version + GeneralUIUtils.findComponentAndClick(origVspName); + GeneralPageElements.clickCheckoutButton(); + GeneralPageElements.clickBrowseButton(); + OnboardingUiUtils.updateVSP(vendorSoftwareProductObject); + + + //Validate that VF name in v1.1 is not changed to new VSP name (it is required to keep the name if at least one certification was done) + Assert.assertTrue(origVspName.equals(ResourceGeneralPage.getNameText())); + + //Validate that VF name in v1.0 is the old VF name + GeneralPageElements.selectVersion("V1.0"); + Assert.assertTrue(origVspName.equals(ResourceGeneralPage.getNameText())); + } + + @Test() + public void UpdateVSPRevertToEarlierVersion() throws Throwable { + // Test Case: 745821 +// 1. Import VSP v1.0 + List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List<String> newRandomFileNamesFromFolder = OnboardingDataProviders.getRandomElements(1, fileNamesFromFolder); + String filePath = FileHandling.getVnfRepositoryPath(); + String vnfFile = newRandomFileNamesFromFolder.get(0); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); + getExtendTest().log(Status.INFO, "Create Vendor License Model " + vendorLicenseModel.getVendorLicenseName()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + getExtendTest().log(Status.INFO, "Create Vendor Software Product " + resourceReqDetails.getName()); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); +// 2. Create VF, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + getExtendTest().log(Status.INFO, "Create VF " + resourceReqDetails.getName()); + Resource resource_v1 = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + getExtendTest().log(Status.INFO, "Certify VF " + resourceReqDetails.getName()); + resource_v1 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); +// 3. Update VSP to v2.0 + getExtendTest().log(Status.INFO, "Update VSP to version 2.0"); + VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails1, filePath, vnfFile); + VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1); +// 4. Update the VF with v2.0 of the VSP + getExtendTest().log(Status.INFO, "Checkout VF v1.1"); + resource_v1 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resourceReqDetails.setUniqueId(resource_v1.getUniqueId()); + resourceReqDetails.setVersion("1.1"); + resourceReqDetails.setCsarVersion("2.0"); + getExtendTest().log(Status.INFO, "Update VF to v2.0"); + resource_v1 = AtomicOperationUtils.updateResource(resourceReqDetails, sdncDesignerDetails, true).left().value(); + getExtendTest().log(Status.INFO, "Certify VF"); + Resource resource_v2 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); +// 5. Update VSP to v3.0 wih the zip from v1.0 + getExtendTest().log(Status.INFO, "Update VSP to version 3.0"); + VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails1, false); + VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1); + getExtendTest().log(Status.INFO, "Checkout VF v2.1"); + resource_v1 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resourceReqDetails.setUniqueId(resource_v1.getUniqueId()); + resourceReqDetails.setVersion("2.1"); + resourceReqDetails.setCsarVersion("3.0"); + getExtendTest().log(Status.INFO, "Update VF to v3.0"); + ResourceRestUtils.updateResource(resourceReqDetails, sdncDesignerDetails1, resource_v1.getUniqueId()); +// 6. Update VF to v3.0 + getExtendTest().log(Status.INFO, "Certify VF"); + Resource resource_v3 = (Resource) AtomicOperationUtils.changeComponentState(resource_v1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); +// 7. Compare versions v1.0 and v3.0 - should be the same +// TODO: Shay add resource comparison. +// 8. Add each of the versions to service, certify - OK + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails1); + getExtendTest().log(Status.INFO, "Create Service " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + getExtendTest().log(Status.INFO, "Add vf's v1 & v2 to service"); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource_v1, service, UserRoleEnum.DESIGNER, true); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer1 = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource_v3, service, UserRoleEnum.DESIGNER, true); + getExtendTest().log(Status.INFO, "Certify Service"); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + System.out.println(""); + } + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "updateList") + public void updateVSPFlowFromOnboardToDistribution(String vnfFile1, String vnfFile2) throws Throwable { + setLog(String.format("Create VSP from %s , update VSP with %s ", vnfFile1, vnfFile2)); +// 1. Import VSP v1.0 + String filePath = org.onap.sdc.frontend.ci.tests.utilities.FileHandling.getUpdateVSPVnfRepositoryPath(); + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", vendorLicenseModel + .getVendorLicenseName())); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile1)); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, sdncDesignerDetails, + vendorLicenseModel, null); +// 2. Create VF, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); + getExtendTest().log(Status.INFO, String.format("Certify the VF")); +// 3. Create Service add to it the certified VF and certify the Service v1.0 + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Certify the Service")); +// 4. Distribute the Service v1.0 + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); +// 5. Update VSP to v2.0 + getExtendTest().log(Status.INFO, "Upgrading the VSP with new file: " + vnfFile2); + VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vendorSoftwareProductObject, sdncDesignerDetails1, filePath, vnfFile2); + getExtendTest().log(Status.INFO, String.format("Validating VSP %s upgrade to version 2.0: ", vnfFile2)); + VendorSoftwareProductRestUtils.validateVspExist(vendorSoftwareProductObject, sdncDesignerDetails1); +// 6. Update the VF with v2.0 of the VSP and certify the VF + getExtendTest().log(Status.INFO, String.format("Checkout the VF %s v1.1 ", resourceReqDetails.getName())); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resourceReqDetails.setUniqueId(resource.getUniqueId()); + resourceReqDetails.setVersion("1.1"); + resourceReqDetails.setCsarVersion("2.0"); + getExtendTest().log(Status.INFO, String.format("Upgrade the VF %s v1.1 with the new VSP %s v2.0 ", resourceReqDetails.getName(), vendorSoftwareProductObject.getName())); + resource = AtomicOperationUtils.updateResource(resourceReqDetails, sdncDesignerDetails, true).left().value(); + getExtendTest().log(Status.INFO, String.format("Certify the VF to v2.0")); + Resource resource_v2 = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); +// 7. Update the Service with the VFi version 2.0 + getExtendTest().log(Status.INFO, String.format("Checkout the Service v1.1")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Change the instance of the VF in the service to VFi v2.0")); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + getExtendTest().log(Status.INFO, String.format("Certify the Service to v2.0")); + service = (org.openecomp.sdc.be.model.Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); +// 8. Distribute the service v2.0 + distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + } + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List") + public void fromOnboardToDistribution(String filePath, String vnfFile) throws Throwable { +// String vnfFile1 = "1-2016-20-visbc3vf-(VOIP)_v2.1.zip"; +// String vnfFile2 = "2-2016-20-visbc3vf-(VOIP)_v2.0.zip"; + setLog(String.format("%s", vnfFile)); +// 1. Import VSP v1.0 + //String filePath = FileHandling.getVnfRepositoryPath(); + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", vendorLicenseModel + .getVendorLicenseName())); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile)); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, + vendorLicenseModel); +// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct); +// 2. Create VF, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); + getExtendTest().log(Status.INFO, String.format("Certify the VF")); +// 3. Create Service add to it the certified VF and certify the Service v1.0 + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Certify the Service")); +// 4. Distribute the Service v1.0 + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + } + + @Test() + public void onboardE2EviaAPI() throws Throwable { +// 1. Import VSP v1.0 + String filePath = FileHandling.getVnfRepositoryPath(); + String vnfFile1 = "1-VF-vCSCF-StateDB-new-update_v3.0.zip"; + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", vendorLicenseModel + .getVendorLicenseName())); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile1)); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile1, filePath, sdncDesignerDetails1, + vendorLicenseModel); +// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile1, createVendorSoftwareProduct); +// 2. Create VF, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); + getExtendTest().log(Status.INFO, String.format("Certify the VF")); +// 3. Create Service add to it the certified VF and certify the Service v1.0 + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Certify the Service")); +// 4. Distribute the Service v1.0 + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardingFlowsUi.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardingFlowsUi.java new file mode 100644 index 0000000000..24451d6d8d --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/OnboardingFlowsUi.java @@ -0,0 +1,626 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.data.providers.OnboardingDataProviders; +import org.onap.sdc.frontend.ci.tests.dataProvider.OnbordingDataProviders; +import org.onap.sdc.backend.ci.tests.datatypes.enums.XnfTypeEnum; +import org.onap.sdc.frontend.ci.tests.flow.CheckSoftwareVersionPropertyFlow; +import org.onap.sdc.frontend.ci.tests.flow.CreateResourceFlow; +import org.onap.sdc.frontend.ci.tests.flow.CreateVspFlow; +import org.onap.sdc.frontend.ci.tests.flow.ImportVspFlow; +import org.onap.sdc.frontend.ci.tests.flow.exception.UiTestFlowRuntimeException; +import org.onap.sdc.frontend.ci.tests.pages.*; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GovernorOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.OpsOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceCreatePage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.TopNavComponent; +import org.onap.sdc.frontend.ci.tests.pages.VspValidationPage; +import org.onap.sdc.frontend.ci.tests.pages.VspValidationResultsPage; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.fail; + +public class OnboardingFlowsUi extends SetupCDTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(OnboardingFlowsUi.class); + private static final String NO_TESTS_ARE_AVAILABLE = "No Tests are Available"; + private static final String NEXT_BUTTON_IS_ENABLED_IT_SHOULD_HAVE_BEEN_ENABLED = + "Next Button is enabled, it should have been enabled"; + private static final String NEXT_BUTTON_IS_DISABLED_IT_SHOULD_HAVE_BEEN_ENABLED = + "Next Button is disabled, it should have been enabled"; + private static final String RESULTS_ARE_NOT_AVAILABLE = "Results are not available"; + private static final String THE_TESTS_ARE_ALREADY_SELECTED_THE_LIST_SHOULD_INITIALLY_BE_EMPTY = + "The tests are already selected, the list should initially be empty"; + private static final String THE_SELECTED_TESTS_ARE_NOT_POPULATED_IN_THE_LIST = + "The selected tests are not populated in the list"; + private static final String THE_SELECTED_TESTS_ARE_NOT_DELETED_FROM_THE_LIST = + "The selected tests are not deleted from the list"; + private static final String NEXT_BUTTON_IS_ENABLED_IT_SHOULD_HAVE_BEEN_DISABLED = + "Next Button is enabled, it should have been disabled"; + + protected static String filePath = FileHandling.getVnfRepositoryPath(); + private Boolean makeDistributionValue; + + @Parameters({"makeDistribution"}) + @BeforeMethod + public void beforeTestReadParams(@Optional("true") String makeDistributionReadValue) { + LOGGER.debug("makeDistribution parameter is '{}'", makeDistributionReadValue); + makeDistributionValue = Boolean.valueOf(makeDistributionReadValue); + } + + @Test + public void onboardVNFTestSanityOneFile() throws Exception { + String vnfFile = "1-VF-vUSP-vCCF-DB_v11.1.zip"; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + runOnboardToDistributionFlow(resourceReqDetails, serviceReqDetails, filePath, vnfFile); + } + + @Test + public void performanceTest() throws Exception { + LOGGER.debug("Start test"); + Long actualTestRunTime = Utils.getActionDuration(() -> { + try { + onboardVNFTestSanityOneFile(); + } catch (final Exception e) { + LOGGER.debug("An error has occurred during the performance test", e); + } + }); + long regularTestRunTime = 400L; + double factor = 1.5; + assertTrue("Expected test run time should be less from " + regularTestRunTime * factor + ", actual time is " + actualTestRunTime, regularTestRunTime * factor > actualTestRunTime); + } + + @Test + public void onboardVNFTestSanity() throws Exception { + List<String> fileNamesFromFolder = OnboardingUtils.getXnfNamesFileList(XnfTypeEnum.VNF); + String vnfFile = fileNamesFromFolder.get(0); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + runOnboardToDistributionFlow(resourceReqDetails, serviceReqDetails, filePath, vnfFile); + } + + @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "Single_VNF") + public void onapOnboardVNFflow(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + runOnboardToDistributionFlow(resourceReqDetails, serviceReqDetails, filePath, vnfFile); + } + + @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "Single_VNF") + public void onapOnboardVSPValidationsSanityFlow(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + String vspName = createNewVSP(filePath, vnfFile); + if (OnboardingUiUtils.getVspValidationCongiguration()) { + goToVspScreen(true, vspName); + + //check links are available + checkVspValidationLinksVisibility(); + + VspValidationPage.navigateToVspValidationPageUsingNavbar(); + assertTrue(NEXT_BUTTON_IS_ENABLED_IT_SHOULD_HAVE_BEEN_DISABLED, + VspValidationPage.checkNextButtonDisabled()); + VspValidationResultsPage.navigateToVspValidationResultsPageUsingNavbar(); + GeneralUIUtils.ultimateWait(); + assertNotNull(GeneralUIUtils.findByText("No Test Performed")); + } else { + goToVspScreen(true, vspName); + + //check links are not available + checkVspValidationLinksInvisibility(); + } + } + + @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "softwareInformationPnf") + public void onboardPNFSoftwareInformationFlow(final String rootFolder, final String pnfFile, + final List<String> softwareVersionList) { + setLog(pnfFile); + final String resourceName = ElementFactory.addRandomSuffixToName(ElementFactory.getResourcePrefix()); + runOnboardPnfSoftwareVersion(resourceName, rootFolder, pnfFile, softwareVersionList); + } + + @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "Single_VNF") + public void onapOnboardVSPValidationsConfigurationChangeCheck(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + String vspName = createNewVSP(filePath, vnfFile); + if (OnboardingUiUtils.getVspValidationCongiguration()) { + goToVspScreen(true, vspName); + //check links are available + checkVspValidationLinksVisibility(); + + //change config + changeVspValidationConfig(false, vspName, OnboardingUiUtils.getVspValidationCongiguration()); + + //check links are not available + checkVspValidationLinksInvisibility(); + } else { + goToVspScreen(true, vspName); + //check links are not available + checkVspValidationLinksInvisibility(); + + changeVspValidationConfig(false, vspName, OnboardingUiUtils.getVspValidationCongiguration()); + + //check links are available + checkVspValidationLinksVisibility(); + } + } + + @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "Single_VNF") + public void onapOnboardVSPCertificationQueryFlow(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + String vspName = createNewVSP(filePath, vnfFile); + if (!OnboardingUiUtils.getVspValidationCongiguration()) { + //change config to true to test the feature + changeVspValidationConfig(true, vspName, OnboardingUiUtils.getVspValidationCongiguration()); + } else { + goToVspScreen(true, vspName); + } + VspValidationPage.navigateToVspValidationPageUsingNavbar(); + assertTrue(NEXT_BUTTON_IS_ENABLED_IT_SHOULD_HAVE_BEEN_DISABLED, VspValidationPage.checkNextButtonDisabled()); + + if (VspValidationPage.checkCertificationQueryExists()) { + VspValidationPage.clickCertificationQueryAll(); + GeneralUIUtils.ultimateWait(); + assertTrue(NEXT_BUTTON_IS_DISABLED_IT_SHOULD_HAVE_BEEN_ENABLED, + !VspValidationPage.checkNextButtonDisabled()); + VspValidationPage.clickOnNextButton(); + GeneralUIUtils.ultimateWait(); + VspValidationPage.clickOnSubmitButton(); + GeneralUIUtils.waitForLoader(); + assertTrue(RESULTS_ARE_NOT_AVAILABLE, VspValidationResultsPage.checkResultsExist()); + } else { + assertNotNull(GeneralUIUtils.findByText("No Certifications Query are Available")); + } + + } + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "Single_Vsp_Test_Csar") + public void onapOnboardVSPComplianceCheckFlow(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + String vspName = createNewVSP(filePath, vnfFile); + if (!OnboardingUiUtils.getVspValidationCongiguration()) { + //change config to true to test the feature + changeVspValidationConfig(true, vspName, OnboardingUiUtils.getVspValidationCongiguration()); + } else { + goToVspScreen(true, vspName); + } + + VspValidationPage.navigateToVspValidationPageUsingNavbar(); + assertTrue(NEXT_BUTTON_IS_ENABLED_IT_SHOULD_HAVE_BEEN_ENABLED, VspValidationPage.checkNextButtonDisabled()); + if (VspValidationPage.checkComplianceCheckExists()) { + VspValidationPage.clickComplianceChecksAll(); + GeneralUIUtils.ultimateWait(); + assertFalse(NEXT_BUTTON_IS_DISABLED_IT_SHOULD_HAVE_BEEN_ENABLED, + VspValidationPage.checkNextButtonDisabled()); + VspValidationPage.clickOnNextButton(); + GeneralUIUtils.ultimateWait(); + VspValidationPage.loadVSPFile(filePath, vnfFile); + VspValidationPage.clickOnSubmitButton(); + GeneralUIUtils.ultimateWait(); + assertTrue(RESULTS_ARE_NOT_AVAILABLE, VspValidationResultsPage.checkResultsExist()); + } else { + assertNotNull(GeneralUIUtils.findByText(NO_TESTS_ARE_AVAILABLE)); + } + + } + + @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "Single_VNF") + public void onapOnboardVSPComplianceCheckOperations(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + String vspName = createNewVSP(filePath, vnfFile); + if (!OnboardingUiUtils.getVspValidationCongiguration()) { + //change config to true to test the feature + changeVspValidationConfig(true, vspName, OnboardingUiUtils.getVspValidationCongiguration()); + } else { + goToVspScreen(true, vspName); + } + + VspValidationPage.navigateToVspValidationPageUsingNavbar(); + assertTrue(NEXT_BUTTON_IS_ENABLED_IT_SHOULD_HAVE_BEEN_ENABLED, VspValidationPage.checkNextButtonDisabled()); + if (VspValidationPage.checkComplianceCheckExists()) { + assertFalse(THE_TESTS_ARE_ALREADY_SELECTED_THE_LIST_SHOULD_INITIALLY_BE_EMPTY, + VspValidationPage.checkSelectedComplianceCheckExists()); + VspValidationPage.clickComplianceChecksAll(); + GeneralUIUtils.ultimateWait(); + assertTrue(THE_SELECTED_TESTS_ARE_NOT_POPULATED_IN_THE_LIST, + VspValidationPage.checkSelectedComplianceCheckExists()); + VspValidationPage.clickComplianceChecksAll(); + GeneralUIUtils.ultimateWait(); + assertFalse(THE_SELECTED_TESTS_ARE_NOT_DELETED_FROM_THE_LIST, + VspValidationPage.checkSelectedComplianceCheckExists()); + } else { + assertNotNull(GeneralUIUtils.findByText(NO_TESTS_ARE_AVAILABLE)); + } + + } + + @Test(dataProviderClass = OnboardingDataProviders.class, dataProvider = "Single_VNF") + public void onapOnboardVSPCertificationQueryOperations(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + String vspName = createNewVSP(filePath, vnfFile); + if (!OnboardingUiUtils.getVspValidationCongiguration()) { + //change config to true to test the feature + changeVspValidationConfig(true, vspName, OnboardingUiUtils.getVspValidationCongiguration()); + } else { + goToVspScreen(true, vspName); + } + + VspValidationPage.navigateToVspValidationPageUsingNavbar(); + assertTrue(NEXT_BUTTON_IS_ENABLED_IT_SHOULD_HAVE_BEEN_ENABLED, VspValidationPage.checkNextButtonDisabled()); + if (VspValidationPage.checkCertificationQueryExists()) { + assertFalse(THE_TESTS_ARE_ALREADY_SELECTED_THE_LIST_SHOULD_INITIALLY_BE_EMPTY, + VspValidationPage.checkSelectedCertificationQueryExists()); + VspValidationPage.clickCertificationQueryAll(); + GeneralUIUtils.ultimateWait(); + assertTrue(THE_SELECTED_TESTS_ARE_NOT_POPULATED_IN_THE_LIST, VspValidationPage.checkSelectedCertificationQueryExists()); + VspValidationPage.clickCertificationQueryAll(); + GeneralUIUtils.ultimateWait(); + assertFalse(THE_SELECTED_TESTS_ARE_NOT_DELETED_FROM_THE_LIST, + VspValidationPage.checkSelectedCertificationQueryExists()); + } else { + assertNotNull(GeneralUIUtils.findByText(NO_TESTS_ARE_AVAILABLE)); + } + + } + + private void checkVspValidationLinksVisibility() { + //check links are available + assertTrue("Validation Link is not available", GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_NAVBAR.getValue())); + assertTrue("Validation Results Link is not available", GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.VspValidationResultsPage.VSP_VALIDATION_RESULTS_PAGE_NAVBAR.getValue())); + } + + private void checkVspValidationLinksInvisibility() { + //check links not available + assertTrue("Validation Link is still available", GeneralUIUtils.isElementInvisibleByTestId(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_NAVBAR.getValue())); + assertTrue("Validation Results Link is still available", GeneralUIUtils.isElementInvisibleByTestId(DataTestIdEnum.VspValidationResultsPage.VSP_VALIDATION_RESULTS_PAGE_NAVBAR.getValue())); + } + + private void changeVspValidationConfig(boolean isCurrentScreenCatalogPage, String vspName, boolean vspConfig) throws Exception { + //change config + OnboardingUiUtils.putVspValidationCongiguration(!vspConfig); + assertTrue(String.format("Failed to set Congiguration to %s", !vspConfig), OnboardingUiUtils.getVspValidationCongiguration() != vspConfig); + + if (!isCurrentScreenCatalogPage) { + GeneralUIUtils.refreshWebpage(); + GeneralUIUtils.ultimateWait(); + } + + goToVspScreen(isCurrentScreenCatalogPage, vspName); + + //revert the config + OnboardingUiUtils.putVspValidationCongiguration(vspConfig); + assertEquals(String.format("Failed to revert Configuration to %s", vspConfig), vspConfig, + OnboardingUiUtils.getVspValidationCongiguration()); + } + + private void goToVspScreen(boolean isCurrentScreenCatalogPage, String vspName) { + if (isCurrentScreenCatalogPage) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.MainMenuButtons.ONBOARD_BUTTON.getValue()); + } + GeneralUIUtils.clickOnElementByText(vspName); + GeneralUIUtils.ultimateWait(); + } + + private String createNewVSP(String filePath, String vnfFile) throws Exception { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + return OnboardingUiUtils.createVSP(resourceReqDetails, vnfFile, filePath, getUser()).getName(); + } + + public void runOnboardPnfSoftwareVersion(final String resourceName, final String rootFolder, + final String pnfFile, final List<String> softwareVersionList) { + final ExtentTest extendTest = getExtendTest(); + + final String swVersionsToString = String.join(", ", softwareVersionList); + + extendTest.log(Status.INFO, + String.format("Creating VSP '%s' by onboarding package '%s' with software version '%s'", + resourceName, pnfFile, swVersionsToString) + ); + final WebDriver webDriver = DriverFactory.getDriver(); + final CreateVspFlow createVspFlow = new CreateVspFlow(webDriver, resourceName, pnfFile, rootFolder); + createVspFlow.run(new TopNavComponent(webDriver)); + + final ImportVspFlow importVspFlow = new ImportVspFlow(webDriver, resourceName); + final ResourceCreatePage resourceCreatePage = + (ResourceCreatePage) importVspFlow.run() + .orElseThrow(() -> new UiTestFlowRuntimeException("Missing expected return ResourceCreatePage")); + + final CreateResourceFlow createResourceFlow = new CreateResourceFlow(webDriver, resourceName); + createResourceFlow.run(resourceCreatePage); + + final CheckSoftwareVersionPropertyFlow checkSoftwareVersionPropertyFlow = + new CheckSoftwareVersionPropertyFlow(webDriver, softwareVersionList); + checkSoftwareVersionPropertyFlow.run(); + + extendTest.log(Status.INFO, + String.format("Successfully onboarded the package '%s' with software version '%s'", + pnfFile, swVersionsToString) + ); + } + + private void runOnboardToDistributionFlow(ResourceReqDetails resourceReqDetails, ServiceReqDetails serviceMetadata, String filePath, String vnfFile) throws Exception { + getExtendTest().log(Status.INFO, "Going to create resource with category: " + resourceReqDetails.getCategories().get(0).getName() + + " subCategory: " + resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName() + + " and service category: " + serviceMetadata.getCategory()); + final String vspName = onboardAndCertify(resourceReqDetails, filePath, vnfFile); + + ServiceUIUtils.createService(serviceMetadata); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + Service containerObject = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, serviceMetadata.getName(), "0.1"); + Resource instanceObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "1.0"); + ComponentInstance componentInstanceDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(instanceObject, containerObject, UserRoleEnum.DESIGNER, true).left().value(); + + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.LifeCyleChangeButtons.CERTIFY.getValue()); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) + .sendKeys("service " + serviceMetadata.getName() + " certified successfully"); + GeneralPageElements.clickOKButton(); + getExtendTest().log(Status.INFO, String.format("Successfully onboarded the package '%s'", vnfFile)); + } + + private void runDistributionFlow(final ServiceReqDetails serviceMetadata) throws Exception { + if (makeDistributionValue) { + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + OpsOperationPage.distributeService(); + OpsOperationPage.displayMonitor(); + + final List<WebElement> rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable(); + AssertJUnit.assertEquals(1, rowsFromMonitorTable.size()); + + OpsOperationPage.waitUntilArtifactsDistributed(0); + } + } + + private String onboardAndCertify(ResourceReqDetails resourceReqDetails, String filePath, String vnfFile) throws Exception { + VendorSoftwareProductObject onboardAndValidate = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser()); + String vspName = onboardAndValidate.getName(); + + DeploymentArtifactPage.getLeftPanel().moveToCompositionScreen(); + ExtentTestActions.addScreenshot(Status.INFO, "TopologyTemplate_" + vnfFile, "The topology template for " + vnfFile + " is as follows : "); + + DeploymentArtifactPage.clickCertifyButton(vspName); + return vspName; + } + + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List") + public void onboardVNFTest(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + ResourceReqDetails resourceReqDetails = ElementFactory.getRandomCategoryResource(); + ServiceReqDetails serviceReqDetails = ElementFactory.getRandomCategoryService(); + runOnboardToDistributionFlow(resourceReqDetails, serviceReqDetails, filePath, vnfFile); + } + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List") + public void onboardVNFShotFlow(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + onboardAndCertify(resourceReqDetails, filePath, vnfFile); + } + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "randomVNF_List") + public void onboardRandomVNFsTest(String filePath, String vnfFile) throws Exception { + setLog(vnfFile); + LOGGER.debug("Vnf File name is: {}", vnfFile); + ResourceReqDetails resourceReqDetails = ElementFactory.getRandomCategoryResource(); + ServiceReqDetails serviceReqDetails = ElementFactory.getRandomCategoryService(); + runOnboardToDistributionFlow(resourceReqDetails, serviceReqDetails, filePath, vnfFile); + } + + + @Test + public void onboardUpdateVNFTest() throws Exception { + List<String> fileNamesFromFolder = FileHandling.getZipFileNamesFromFolder(filePath); + String vnfFile = fileNamesFromFolder.get(0); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, filePath, vnfFile, getUser()); + String vspName = vsp.getName(); + ResourceGeneralPage.clickCertifyButton(vspName); + + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CompositionPage.searchForElement(vspName); + CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vspName); + assertNotNull(vfElement); + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); + + if (!HomePage.navigateToHomePage()) { + fail("Could not go to the home page"); + } + + ///update flow + String updatedVnfFile = fileNamesFromFolder.get(1); + + getExtendTest().log(Status.INFO, String.format("Going to update the VNF with %s......", updatedVnfFile)); + // update VendorSoftwareProduct + OnboardingUiUtils.updateVnfAndValidate(filePath, vsp, updatedVnfFile, getUser()); + ResourceGeneralPage.clickCertifyButton(vspName); + + // replace exiting VFI in service with new updated + + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + serviceCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(serviceCanvasManager, vfElement, "2.0"); + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", 1, getUser()); + + ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GovernorOperationPage.approveService(serviceMetadata.getName()); + + + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + OpsOperationPage.distributeService(); + OpsOperationPage.displayMonitor(); + + List<WebElement> rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable(); + AssertJUnit.assertEquals(1, rowsFromMonitorTable.size()); + + OpsOperationPage.waitUntilArtifactsDistributed(0); + getExtendTest().log(Status.INFO, String.format("Onboarding %s test is passed ! ", vnfFile)); + } + + + @Test + public void threeVMMSCsInServiceTest() throws Exception { + String pathFile = FileHandling.getFilePath("VmmscArtifacts"); + final String[] list = new File(pathFile).list(); + assertNotNull("Did not find vMMSCs", list); + assertFalse("Did not find vMMSCs", list.length == 0); + List<String> vmmscList = Arrays.stream(list).filter(e -> e.contains("vmmsc") && e.endsWith(".zip")) + .collect(Collectors.toList()); + assertFalse("Did not find vMMSCs", vmmscList.isEmpty()); + + Map<String, String> vspNames = new HashMap<>(); + for (String vnfFile : vmmscList) { + String msg = String.format("Going to onboard the VNF %s", vnfFile); + getExtendTest().log(Status.INFO, msg); + LOGGER.info(msg); + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + VendorSoftwareProductObject createVendorSoftwareProduct = VendorSoftwareProductRestUtils + .createVendorSoftwareProduct(resourceReqDetails, vnfFile, pathFile, getUser(), vendorLicenseModel); + + getExtendTest().log(Status.INFO, String.format("Searching for onboarded %s", vnfFile)); + HomePage.showVspRepository(); + getExtendTest().log(Status.INFO, String.format("Going to import %s......", vnfFile.substring(0, vnfFile.indexOf(".")))); + OnboardingUiUtils.importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(pathFile, vnfFile); + + String vspName = createVendorSoftwareProduct.getName(); + DeploymentArtifactPage.clickCertifyButton(vspName); + vspNames.put(vnfFile, vspName); + } + + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager serviceCanvasManager = CanvasManager.getCanvasManager(); + + for (String vsp : vspNames.values()) { + CompositionPage.searchForElement(vsp); + CanvasElement vfElement = serviceCanvasManager.createElementOnCanvas(vsp); + assertNotNull(vfElement); + } + ServiceVerificator.verifyNumOfComponentInstances(serviceMetadata, "0.1", vspNames.values().size(), getUser()); + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Info_" + getExtendTest().getModel().getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.INFO, "Three kinds of vMMSC are in canvas now." + getExtendTest().addScreenCaptureFromPath(absolutePath)); + + ServiceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GovernorOperationPage.approveService(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + OpsOperationPage.distributeService(); + OpsOperationPage.displayMonitor(); + + List<WebElement> rowsFromMonitorTable = OpsOperationPage.getRowsFromMonitorTable(); + AssertJUnit.assertEquals(1, rowsFromMonitorTable.size()); + + OpsOperationPage.waitUntilArtifactsDistributed(0); + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PNF.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PNF.java new file mode 100644 index 0000000000..193f731403 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PNF.java @@ -0,0 +1,431 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.TypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.GovernorOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.OpsOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.ToscaArtifactsPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.List; + +import static org.testng.Assert.assertTrue; + +public class PNF extends SetupCDTest { + + private String filePath; + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath(""); + } + + @BeforeMethod + public void beforeTest() { + System.out.println("File repository is : " + filePath); + getExtendTest().log(Status.INFO, "File repository is : " + filePath); + } + + @Test + public void updatePNF() throws Exception { + + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + // update Resource + ResourceReqDetails updatedResource = new ResourceReqDetails(); + updatedResource.setName(ElementFactory.getResourcePrefix() + "UpdatedName" + pnfMetaData.getName()); + updatedResource.setDescription("kuku"); + updatedResource.setVendorName("updatedVendor"); + updatedResource.setVendorRelease("updatedRelease"); + updatedResource.setContactId("ab0001"); + updatedResource.setCategories(pnfMetaData.getCategories()); + updatedResource.setVersion("0.1"); + updatedResource.setResourceType(ResourceTypeEnum.VF.getValue()); + List<String> newTags = pnfMetaData.getTags(); + newTags.remove(pnfMetaData.getName()); + newTags.add(updatedResource.getName()); + updatedResource.setTags(newTags); + ResourceUIUtils.updateResource(updatedResource, getUser()); + + VfVerificator.verifyVFMetadataInUI(updatedResource); + VfVerificator.verifyVFUpdated(updatedResource, getUser()); + } + + @Test + public void addUpdateDeleteInformationalArtifactPNFTest() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", InformationalArtifactPage.checkElementsCountInTable(1)); + + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifact.getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + AssertJUnit.assertTrue("artifact " + informationalArtifact.getArtifactLabel() + "is not deleted", InformationalArtifactPage.checkElementsCountInTable(0)); + } + + @Test + public void addPropertiesToVfcInstanceInPNFTest() throws Exception { + + if (true) { +// throw new SkipException("Open bug 373762, can't update properties on CP or VFC instance on Composition screen"); + SetupCDTest.getExtendTest().log(Status.INFO, "Open bug 373762, can't update properties on CP or VFC instance on Composition screen"); + } + + String fileName = "CP02.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try { + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement cpElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + vfCanvasManager.clickOnCanvaElement(cpElement); + CompositionPage.showPropertiesAndAttributesTab(); + List<WebElement> properties = CompositionPage.getProperties(); + String propertyValue = "abc123"; + for (int i = 0; i < 2; i++) { + WebElement findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label")); + findElement.click(); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue); + PropertiesPage.getPropertyPopup().clickSave(); + + findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-value")); + SetupCDTest.getExtendTest().log(Status.INFO, "Validating properties"); + AssertJUnit.assertTrue(findElement.getText().equals(propertyValue)); + } + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void changeInstanceVersionPNFTest() throws Exception { + + ResourceReqDetails atomicResourceMetaData = null; + ResourceReqDetails pnfMetaData = null; + CanvasManager vfCanvasManager; + CanvasElement cpElement = null; + String fileName = "CP03.yml"; + try { + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.CP, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(atomicResourceMetaData.getName()); + + pnfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.PNF, getUser()); + ResourceUIUtils.createPNF(pnfMetaData, getUser()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + cpElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + //TODO Andrey should click on certify button + CompositionPage.clickCertifyButton(pnfMetaData.getName()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + AssertJUnit.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + TesterOperationPage.certifyComponent(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + GeneralUIUtils.findComponentAndClick(pnfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, cpElement, "1.0"); + + //verfication + VfVerificator.verifyInstanceVersion(pnfMetaData, getUser(), atomicResourceMetaData.getName(), "1.0"); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + @Test + public void verifyToscaArtifactsExistPNFTest() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + final int numOfToscaArtifacts = 2; + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + AssertJUnit.assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); + + for (int i = 0; i < numOfToscaArtifacts; i++) { + String typeFromScreen = ToscaArtifactsPage.getArtifactType(i); + AssertJUnit.assertTrue(typeFromScreen.equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) || typeFromScreen.equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())); + } + //TODO Andrey should click on certify button + ToscaArtifactsPage.clickCertifyButton(pnfMetaData.getName()); + pnfMetaData.setVersion("1.0"); + VfVerificator.verifyToscaArtifactsInfo(pnfMetaData, getUser()); + } + + @Test + public void pnfCertificationTest() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + String vfName = pnfMetaData.getName(); + + ResourceGeneralPage.clickCheckinButton(vfName); + GeneralUIUtils.findComponentAndClick(vfName); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(vfName); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfName); + TesterOperationPage.certifyComponent(vfName);*/ + + pnfMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(pnfMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + /*reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + GeneralUIUtils.findComponentAndClick(vfName); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void deletePNFTest() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + GeneralPageElements.clickTrashButtonAndConfirm(); + + pnfMetaData.setVersion("0.1"); + VfVerificator.verifyVfDeleted(pnfMetaData, getUser()); + } + + @Test + public void revertPNFMetadataTest() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + ResourceReqDetails pvfRevertDetails = new ResourceReqDetails(); + pvfRevertDetails.setName("ciUpdatedName"); + pvfRevertDetails.setDescription("kuku"); + pvfRevertDetails.setCategories(pnfMetaData.getCategories()); + pvfRevertDetails.setVendorName("updatedVendor"); + pvfRevertDetails.setVendorRelease("updatedRelease"); + ResourceUIUtils.fillResourceGeneralInformationPage(pvfRevertDetails, getUser(), false); + + GeneralPageElements.clickRevertButton(); + + VfVerificator.verifyVFMetadataInUI(pnfMetaData); + } + + @Test + public void checkoutPnfTest() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + ResourceGeneralPage.clickCheckinButton(pnfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(pnfMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + + pnfMetaData.setVersion("0.2"); + VfVerificator.verifyVFLifecycle(pnfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(pnfMetaData.getName()); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(pnfMetaData.getName()); + TesterOperationPage.certifyComponent(pnfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + GeneralUIUtils.findComponentAndClick(pnfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + pnfMetaData.setVersion("1.1"); + pnfMetaData.setUniqueId(null); + VfVerificator.verifyVFLifecycle(pnfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + } + + public ResourceReqDetails createPNFWithGenerateName() throws Exception { + ResourceReqDetails pnfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.PNF, getUser()); + ResourceUIUtils.createPNF(pnfMetaData, getUser()); + return pnfMetaData; + } + + @Test + public void verifyPNF_UI_Limitations() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + SetupCDTest.getExtendTest().log(Status.INFO, "Validating Deployment Artifact Left Side Menu not exist"); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId("Deployment ArtifactLeftSideMenu")); + SetupCDTest.getExtendTest().log(Status.INFO, "Validating Deployment Left Side Menu not exist"); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId("DeploymentLeftSideMenu")); + } + + @Test + public void filteringCatalogByPNF() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + String pnfName = pnfMetaData.getName(); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(pnfName); + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(pnfName); + TesterOperationPage.certifyComponent(pnfName);*/ + + pnfMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(pnfMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + /*reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogFilterTypeChecBox(TypesEnum.valueOf("PNF")); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating resource %s found", pnfName)); + GeneralUIUtils.clickOnElementByTestId(pnfName); + } + + @Test + public void addPNFtoServiceAndDistribute() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement("ContrailPort"); + vfCanvasManager.createElementOnCanvas("ContrailPort"); + + String pnfName = pnfMetaData.getName(); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(pnfName); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(pnfName); + TesterOperationPage.certifyComponent(pnfName);*/ + + pnfMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(pnfMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + /*reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(pnfName); + CanvasElement pnfElement = canvasManager.createElementOnCanvas(pnfName); + CanvasElement networkElement = canvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.CONTRAIL_VIRTUAL_NETWORK); + + canvasManager.linkElements(pnfElement, networkElement); + String serviceName = serviceMetadata.getName(); + ServiceGeneralPage.clickSubmitForTestingButton(serviceName); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceName); + TesterOperationPage.certifyComponent(serviceName); + + reloginWithNewRole(UserRoleEnum.GOVERNOR); + GeneralUIUtils.findComponentAndClick(serviceName); + GovernorOperationPage.approveService(serviceName); + + reloginWithNewRole(UserRoleEnum.OPS); + GeneralUIUtils.findComponentAndClick(serviceName); + OpsOperationPage.distributeService(); + } + + @Test + public void checkInfomationArtifactUploadLimitation() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + List<WebElement> webElements = GeneralUIUtils.getWebElementsListBy(By.xpath(DataTestIdEnum.ArtifactPageEnum.ADD_OTHER_ARTIFACT_BUTTON.getValue())); + int numberOfElements = webElements.size(); + String buttonText = webElements.get(0).getText(); + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying only one button exist: Add Other Artifact"); + assertTrue(buttonText.equalsIgnoreCase(("Add Other Artifact"))); + assertTrue(1 == numberOfElements, "There should be only one option for uploading artifact in PNF"); + } + + @Test + public void checkNonCPVLObjectsNotExistInComosition() throws Exception { + ResourceReqDetails pnfMetaData = createPNFWithGenerateName(); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + String pnfName = pnfMetaData.getName(); + // Searching for VFC element and make sure it not exist in PNF composition (Only VL/CP are allowed). + CompositionPage.searchForElement("BlockStorage"); + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying Element found"); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId("BlockStorage")); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PortMirroring.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PortMirroring.java new file mode 100644 index 0000000000..1de9853c38 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PortMirroring.java @@ -0,0 +1,613 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.HomeUtils; +import org.onap.sdc.frontend.ci.tests.utilities.PortMirroringUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.FileHandling; +import org.onap.sdc.frontend.ci.tests.verificator.PortMirroringVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.ConnectionWizardPopUpObject; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.PortMirrioringConfigurationObject; +import org.onap.sdc.frontend.ci.tests.datatypes.PortMirroringEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.ServiceContainer; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; + +import java.io.File; + +import static org.testng.Assert.assertTrue; + +public class PortMirroring extends SetupCDTest { + + private static final int THREAD_SLEEP_TIME = 3000; + + @Test + public void createPortMirroringConfigurationServiceProxy() throws Throwable { + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails(); + CanvasManager canvasManager = portMirrioringConfigurationObject.getCanvasManager(); + CanvasElement serviceElementVmmeSourceName = portMirrioringConfigurationObject.getServiceElementVmmeSourceName(); + String vmmeSourceName = portMirrioringConfigurationObject.getVmmeSourceName(); + CanvasElement serviceElementVprobeCollector = portMirrioringConfigurationObject.getServiceElementVprobeCollector(); + String vprobeSourceName = portMirrioringConfigurationObject.getVprobeSourceName(); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating links between elements were created"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2); + + canvasManager.clickOnCanvaElement(serviceElementVmmeSourceName); + PortMirroringVerificator.validatingProxyServiceNameAndType(vmmeSourceName, "0"); + + canvasManager.clickOnCanvaElement(serviceElementVprobeCollector); + PortMirroringVerificator.validatingProxyServiceNameAndType(vprobeSourceName, "0"); + } + + @Test + public void distributePortMirroringConfigurationServiceProxy() throws Throwable { + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails(); + Service service = portMirrioringConfigurationObject.getService(); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating links between elements were created"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2); + + getExtendTest().log(Status.INFO, String.format("Going to certify the Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Service is certified")); + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + } + + @Test + public void createPortMirroringByPolicyServiceProxy() throws Throwable { + //Using API onboard and certify 2 zip files Source: vmmme and Collector: Vprobe + String filePath = FileHandling.getPortMirroringRepositoryPath(); + ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, "2016-227_vmme_vmme_30_1610_e2e.zip"); + + // create service with required pnf's and certify it + Resource resourceCisco = PortMirroringUtils.generatePNFAndUpdateInput(PortMirroringEnum.CISCO_VENDOR_NAME.getValue(), PortMirroringEnum.CISCO_VENDOR_MODEL_NUMBER.getValue(), getUser()); + Resource resourceAPCON1 = PortMirroringUtils.generatePNFAndUpdateInput(PortMirroringEnum.APCON1_VENDOR_NAME.getValue(), PortMirroringEnum.APCON1_VENDOR_MODEL_NUMBER.getValue(), getUser()); + Resource resourceAPCON2 = PortMirroringUtils.generatePNFAndUpdateInput(PortMirroringEnum.APCON2_VENDOR_NAME.getValue(), PortMirroringEnum.APCON2_VENDOR_MODEL_NUMBER.getValue(), getUser()); + + ServiceReqDetails serviceReqDetailsCollector = ElementFactory.getDefaultService(); + serviceReqDetailsCollector.setServiceType(PortMirroringEnum.SERVICE_TYPE.getValue()); + getExtendTest().log(Status.INFO, String.format("Creating collector service %s (PNF container)", serviceReqDetailsCollector.getName())); + Service serviceCollector = AtomicOperationUtils.createCustomService(serviceReqDetailsCollector, UserRoleEnum.DESIGNER, true).left().value(); + + getExtendTest().log(Status.INFO, String.format("Adding pnf's: %s,%s,%s to service %s", resourceCisco.getName(), resourceAPCON1.getName(), resourceAPCON2.getName(), serviceCollector.getName())); + + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceCisco, serviceCollector, UserRoleEnum.DESIGNER, true, "80", "80"); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceAPCON1, serviceCollector, UserRoleEnum.DESIGNER, true, "80", "200"); + AtomicOperationUtils.addComponentInstanceToComponentContainer(resourceAPCON2, serviceCollector, UserRoleEnum.DESIGNER, true, "200", "200"); + + serviceCollector = (Service) AtomicOperationUtils.changeComponentState(serviceCollector, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + // create container service + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + String vmmeSourceName = serviceContainerVmme_Source.getService().getName(); + String collectorServiceName = serviceCollector.getName(); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CompositionPage.searchForElement(vmmeSourceName); + CanvasElement serviceElementVmmeSource = canvasManager.createElementOnCanvas(vmmeSourceName); + + CompositionPage.searchForElement(collectorServiceName); + CanvasElement serviceElementCollectorService = canvasManager.createElementOnCanvas(collectorServiceName); + + CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + + ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", + "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), + PortMirroringEnum.PMCP_SOURCE_CAP.getValue()); + + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSource, + portMirroringConfigurationByPolicyElement, + connectionWizardPopUpObjectVMME); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating link between elements was created"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 1); + + canvasManager.clickOnCanvaElement(serviceElementVmmeSource); + PortMirroringVerificator.validatingProxyServiceNameAndType(vmmeSourceName, "0"); + + getExtendTest().log(Status.INFO, "Adding properties to PMCP"); + + SetupCDTest.getExtendTest().log(Status.INFO, "Open bug 373762, can't update properties on CP or VFC instance on Composition screen"); + + canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement); + CompositionPage.showPropertiesAndAttributesTab(); + CompositionPage.setSingleProperty(DataTestIdEnum.PortMirroring.COLLECTOR_NODE.getValue(), PortMirroringUtils.createproxyinstanceservicename(collectorServiceName, "1")); + CompositionPage.setSingleProperty(DataTestIdEnum.PortMirroring.EQUIP_MODEL.getValue(), PortMirroringEnum.CISCO_VENDOR_MODEL_NUMBER.getValue()); + CompositionPage.setSingleProperty(DataTestIdEnum.PortMirroring.EQUIP_VENDOR.getValue(), PortMirroringEnum.CISCO_VENDOR_NAME.getValue()); + + // Distribute the Port Mirroning Configuration By Policy + getExtendTest().log(Status.INFO, String.format("Going to certify the Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Service is certified")); + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + } + + @Test + public void deletePMCPLink() throws Throwable { + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + String filePath = FileHandling.getPortMirroringRepositoryPath(); + ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, "2016-227_vmme_vmme_30_1610_e2e.zip"); + + String vmmeSourceName = serviceContainerVmme_Source.getService().getName(); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CompositionPage.searchForElement(vmmeSourceName); + CanvasElement serviceElementVmmeSource = canvasManager.createElementOnCanvas(vmmeSourceName); + + CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + + ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", + "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), + PortMirroringEnum.PMCP_SOURCE_CAP.getValue()); + + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSource, + portMirroringConfigurationByPolicyElement, + connectionWizardPopUpObjectVMME); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating link between elements was created"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 1); + + canvasManager.openLinkPopupReqsCapsConnection(serviceElementVmmeSource, portMirroringConfigurationByPolicyElement); + canvasManager.closeLinkPopupReqsCapsConnection(); + canvasManager.deleteLinkPopupReqsCapsConnection(serviceElementVmmeSource, portMirroringConfigurationByPolicyElement); + + getExtendTest().log(Status.INFO, "Validating link deleted"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 0); + } + + @Test + public void verifyPMCNotExistInVF() throws Exception { + Resource resource = PortMirroringUtils.getresourcebytype(ResourceTypeEnum.VF, "VF", "VendorModel"); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + + GeneralUIUtils.findComponentAndClick(resource.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); + + getExtendTest().log(Status.INFO, "Verify that Port Mirroring Configuration and Configuration by Policy doesn't exist for VF "); + boolean isPMCFound = GeneralUIUtils.isElementInvisibleByTestId(DataTestIdEnum.PortMirroring.PMC_NAME_IN_PALLETE.getValue()); + boolean isPMCPFound = GeneralUIUtils.isElementInvisibleByTestId(DataTestIdEnum.PortMirroring.PMCP_NAME_IN_PALLETE.getValue()); + + assertTrue(isPMCFound); + assertTrue(isPMCPFound); + } + + @Test + public void verifyPMCPTabs() throws Exception { + + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement); + + PortMirroringVerificator.validateGeneralInfo(); + PortMirroringVerificator.validateReqsAndCapsTabExist(); + } + + + @Test + public void editPMCPName() throws Exception { + + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + + canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement); + + getExtendTest().log(Status.INFO, "Edit PMCP Name"); + canvasManager.updateElementNameInCanvas(portMirroringConfigurationByPolicyElement, PortMirroringEnum.PMCP_NEWNAME.getValue()); + + PortMirroringVerificator.validateElementName(PortMirroringEnum.PMCP_NEWNAME.getValue()); + } + + + @Test + public void deletePMCP() throws Exception { + + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + + canvasManager.clickOnCanvaElement(portMirroringConfigurationByPolicyElement); + + getExtendTest().log(Status.INFO, String.format("Delete element %s", portMirroringConfigurationByPolicyElement.getElementType())); + canvasManager.deleteElementFromCanvas(portMirroringConfigurationByPolicyElement); + + PortMirroringVerificator.validateElementName(service.getName()); + } + + @Test + public void createPortMirroringConfigurationMulipleInstances() throws Throwable { + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails(); + CanvasElement serviceElementVmmeSourceName = portMirrioringConfigurationObject.getServiceElementVmmeSourceName(); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating 2 links between elements were created"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + + getExtendTest().log(Status.INFO, "Adding second PMC to composition"); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); + + ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_SOURCE_CAP.getValue()); + + getExtendTest().log(Status.INFO, "Connect VMME to PMC again"); + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, portMirroringConfigurationElement, + connectionWizardPopUpObjectVMME); + + getExtendTest().log(Status.INFO, "Connect VMME to PMC again"); + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, portMirroringConfigurationElement, + connectionWizardPopUpObjectVMME); + + getExtendTest().log(Status.INFO, "Validating 4 links between elements exist"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 4); + + getExtendTest().log(Status.INFO, "Adding second PMCP to composition"); + CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + + ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME_PMCP = new ConnectionWizardPopUpObject("", + "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), + PortMirroringEnum.PMCP_SOURCE_CAP.getValue()); + + getExtendTest().log(Status.INFO, "Connect VMME to PMCP again"); + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, portMirroringConfigurationByPolicyElement, + connectionWizardPopUpObjectVMME_PMCP); + + getExtendTest().log(Status.INFO, "Connect VMME to PMCP again"); + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, portMirroringConfigurationByPolicyElement, + connectionWizardPopUpObjectVMME_PMCP); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating 6 links between elements exist"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 6); + } + + @Test + public void downloadArtifactFromPMCService() throws Throwable { + //Scenario of bug 362271 + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails(); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + + ServiceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.TOSCA_MODEL.getValue()); + File latestFilefromDir = org.onap.sdc.frontend.ci.tests.utilities.FileHandling.getLastModifiedFileNameFromDir(); + String actualToscaModelFilename = latestFilefromDir.getName(); + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.TOSCA_TEMPLATE.getValue()); + latestFilefromDir = org.onap.sdc.frontend.ci.tests.utilities.FileHandling.getLastModifiedFileNameFromDir(); + String actualToscaTemplateFilename = latestFilefromDir.getName(); + + String expectedToscaModelFilename = String.format("service-%s-csar.csar", serviceReqDetails.getName()); + String expectedToscaTemplateFilename = String.format("service-%s-template.yml", serviceReqDetails.getName()); + + getExtendTest().log(Status.INFO, "Validating tosca artifact downloaded successfully"); + AssertJUnit.assertTrue(actualToscaModelFilename.equalsIgnoreCase(expectedToscaModelFilename)); + AssertJUnit.assertTrue(actualToscaTemplateFilename.equalsIgnoreCase(expectedToscaTemplateFilename)); + } + + @Test + public void checkoutMirroringConfigurationServiceProxyAndDeletePMC() throws Throwable { + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails(); + Service service = portMirrioringConfigurationObject.getService(); + CanvasElement portMirroringConfigurationElement = portMirrioringConfigurationObject.getPortMirroringConfigurationElement(); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating links between elements were created"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2); + + getExtendTest().log(Status.INFO, String.format("Going to certify the Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + getExtendTest().log(Status.INFO, String.format("Checkout Port Mirroring Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + HomeUtils.findComponentAndClickByVersion(service.getName(), "1.1"); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + GeneralUIUtils.ultimateWait(); + canvasManager.clickOnCanvaElement(portMirroringConfigurationElement); + getExtendTest().log(Status.INFO, String.format("Delete element %s", portMirroringConfigurationElement.getElementType())); + canvasManager.deleteElementFromCanvas(portMirroringConfigurationElement); + + PortMirroringVerificator.validateElementName(service.getName()); + getExtendTest().log(Status.INFO, "Validating 0 links after delete the port mirroring element"); + serviceReqDetails.setVersion("1.1"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 0); + + getExtendTest().log(Status.INFO, String.format("Going to certify the Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + getExtendTest().log(Status.INFO, String.format("Service is certified")); + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + } + + @Test + public void updatePortMirroringServiceInstance() throws Throwable { + + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + Service service = portMirrioringConfigurationObject.getService(); + CanvasElement vmmeCanvasElement = portMirrioringConfigurationObject.getServiceElementVmmeSourceName(); + + getExtendTest().log(Status.INFO, String.format("Going to certify the Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + Service serviceContainerVmme_Source = portMirrioringConfigurationObject.getServiceContainerVmme_Source(); + getExtendTest().log(Status.INFO, String.format("Checkout the vmme Service")); + serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Going to certify the vmme Service")); + serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + getExtendTest().log(Status.INFO, String.format("Checkout Port Mirroring Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + HomeUtils.findComponentAndClickByVersion(service.getName(), "1.1"); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + getExtendTest().log(Status.INFO, String.format("Change vmme source %s instance to version 2.0", serviceContainerVmme_Source.getName())); + CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "2.0", false); + + getExtendTest().log(Status.INFO, String.format("Going to certify the Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + getExtendTest().log(Status.INFO, String.format("Service is certified")); + Boolean distributeAndValidateService = AtomicOperationUtils.distributeAndValidateService(service); + getExtendTest().log(Status.INFO, String.format("Distribute and validate the Service")); + AssertJUnit.assertTrue("Distribution status is " + distributeAndValidateService, distributeAndValidateService); + } + + @Test + public void updateLinkPropertiesPortMirroringService() throws Throwable { + + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + getExtendTest().log(Status.INFO, String.format("Creating container service %s", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + String filePath = FileHandling.getPortMirroringRepositoryPath(); + ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, "2016-227_vmme_vmme_30_1610_e2e.zip"); + + String vmmeSourceName = serviceContainerVmme_Source.getService().getName(); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CompositionPage.searchForElement(vmmeSourceName); + CanvasElement serviceElementVmmeSource = canvasManager.createElementOnCanvas(vmmeSourceName); + + CompositionPage.searchForElement(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationByPolicyElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMCP_ELEMENT_IN_PALLETE.getValue()); + + ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", + "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), + PortMirroringEnum.PMCP_SOURCE_CAP.getValue()); + + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSource, + portMirroringConfigurationByPolicyElement, + connectionWizardPopUpObjectVMME); + + serviceReqDetails.setVersion("0.1"); + getExtendTest().log(Status.INFO, "Validating link between elements was created"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 1); + + canvasManager.openLinkPopupReqsCapsConnection(serviceElementVmmeSource, portMirroringConfigurationByPolicyElement); + + getExtendTest().log(Status.INFO, "Fill link properties with data"); + GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.NETWORK_ROLE_XPATH.getValue(), PortMirroringEnum.NETWORK_ROLE_VALUE.getValue()); + GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.NFC_TYPE_XPATH.getValue(), PortMirroringEnum.NFC_TYPE_VALUE.getValue()); + GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.PPS_CAPACITY_XPATH.getValue(), PortMirroringEnum.PPS_CAPACITY_VALUE.getValue()); + GeneralUIUtils.setTextInElementByXpath(PortMirroringEnum.NF_TYPE_XPATH.getValue(), PortMirroringEnum.NF_TYPE_VALUE.getValue()); + GeneralUIUtils.ultimateWait(); + + canvasManager.clickSaveOnLinkPopup(); + Thread.sleep(THREAD_SLEEP_TIME); //Temp solution. Don't remove. + canvasManager.openLinkPopupReqsCapsConnection(serviceElementVmmeSource, portMirroringConfigurationByPolicyElement); + + PortMirroringVerificator.validateLinkProperties(); + } + + @Test + public void restorePortMirroringServiceLink() throws Throwable { + + //Scenario is taken from bug 361475 - Second Scenario + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails(); + Service service = portMirrioringConfigurationObject.getService(); + CanvasElement vmmeCanvasElement = portMirrioringConfigurationObject.getServiceElementVmmeSourceName(); + Service serviceContainerVmme_Source = portMirrioringConfigurationObject.getServiceContainerVmme_Source(); + + getExtendTest().log(Status.INFO, String.format("Checkout the vmme Service")); + serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Going to certify the vmme Service")); + serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + HomeUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 2.0", serviceContainerVmme_Source.getName())); + CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "2.0", false); + + getExtendTest().log(Status.INFO, "Validating 1 link exist after change version to the vmme service (Newer version)"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2); + + getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 1.0", serviceContainerVmme_Source.getName())); + CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "1.0", false); + + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 2); + } + + @Test + public void restoreServiceVersionOnContainerService() throws Throwable { + //Scenario is taken from bug 361475 - First Scenario + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(false); + ServiceReqDetails serviceReqDetails = portMirrioringConfigurationObject.getServiceReqDetails(); + Service service = portMirrioringConfigurationObject.getService(); + CanvasElement vmmeCanvasElement = portMirrioringConfigurationObject.getServiceElementVmmeSourceName(); + Service serviceContainerVmme_Source = portMirrioringConfigurationObject.getServiceContainerVmme_Source(); + Service serviceContainerVprobe_Vprobe_Collector = portMirrioringConfigurationObject.getServiceContainerVprobe_Collector(); + CanvasElement vprobeCanvasElement = portMirrioringConfigurationObject.getServiceElementVprobeCollector(); + + + getExtendTest().log(Status.INFO, String.format("Checkout the vmme Service")); + serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + getExtendTest().log(Status.INFO, String.format("Going to certify the vmme Service")); + serviceContainerVmme_Source = (Service) AtomicOperationUtils.changeComponentState(serviceContainerVmme_Source, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.ultimateWait(); + HomeUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + canvasManager.linkElements(vmmeCanvasElement, vprobeCanvasElement); + + getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 2.0", serviceContainerVmme_Source.getName())); + CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "2.0", false); + + getExtendTest().log(Status.INFO, "Validating 1 link exist after change version to the vmme service (Newer version)"); + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 3); + + getExtendTest().log(Status.INFO, String.format("Changing vmme source %s instance to version 1.0", serviceContainerVmme_Source.getName())); + CompositionPage.changeComponentVersion(canvasManager, vmmeCanvasElement, "1.0", false); + + ServiceVerificator.verifyLinkCreated(serviceReqDetails, getUser(), 3); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } +} + + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Product.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Product.java new file mode 100644 index 0000000000..5e252423fe --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Product.java @@ -0,0 +1,74 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.backend.ci.tests.datatypes.ProductReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.ProductGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ProductUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.testng.annotations.Test; + +/** + * @author al714h + */ + +public class Product extends SetupCDTest { + + + @Test + public void createProductAndAddCertifiedServiceInstance() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ProductReqDetails productReqDetails = ElementFactory.getDefaultProduct(); + + ServiceUIUtils.createService(serviceMetadata); + GeneralPageElements.clickSubmitForTestingButton(serviceMetadata.getName()); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + reloginWithNewRole(UserRoleEnum.PRODUCT_MANAGER1); + ProductUIUtils.createProduct(productReqDetails, getUser()); + ProductGeneralPage.getProductLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement canvasElement = CompositionPage.addElementToCanvasScreen(serviceMetadata.getName(), canvasManager); + canvasManager.clickOnCanvaElement(canvasElement); + } + + @Test + public void loginAsProductStrateger() throws Exception { + reloginWithNewRole(UserRoleEnum.PRODUCT_STRATEGIST1); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignment.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignment.java new file mode 100644 index 0000000000..5a13b67667 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignment.java @@ -0,0 +1,581 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesAssignmentPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertyNameBuilder; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.frontend.ci.tests.verificator.PropertiesAssignmentVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + + +public class PropertiesAssignment extends SetupCDTest { + + private static String filePath; + private static String csarFile = "PCRF_OS_FIXED.csar"; + private static String csarFile1 = "437285.csar"; + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath(""); + } + + @BeforeMethod + public void beforeTest() { + System.out.println("File repository is : " + filePath); + getExtendTest().log(Status.INFO, "File repository is : " + filePath); + } + + + //VF - Simple Properties Tests + @Test + public void declareAndDeleteInputVfTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_psm"; + String propertyName = "service_template_filter"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.clickOnDeclareButton(); + GeneralUIUtils.ultimateWait(); + AssertJUnit.assertTrue(PropertiesAssignmentPage.isPropertyChecked(propertyName)); + + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.findInput(componentName, propertyName); + PropertiesAssignmentPage.clickOnDeleteInputButton(); + PropertiesAssignmentPage.clickOnDeleteInputDialogConfirmationButton(); + PropertiesAssignmentPage.clickOnPropertiesTab(); + PropertiesAssignmentPage.findProperty(propertyName); + AssertJUnit.assertFalse(PropertiesAssignmentPage.isPropertyChecked(propertyName)); + + + } + + + @Test + public void editAndSaveSimplePropertyValueTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_psm"; + String propertyNameString = PropertyNameBuilder.buildSimpleField("nfc_function"); + String propertyNameInt = PropertyNameBuilder.buildSimpleField("index_value"); + String propertyValueString = "abc"; + String propertyValueInt = "123"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType( + "ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit simple properties values and save + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.editPropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentPage.editPropertyValue(propertyNameInt, propertyValueInt); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that properties values are saved + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameInt, propertyValueInt); + } + + @Test + public void editAndSaveBooleanPropertyValueTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "oam_volume_0"; + String propertyNameTrue = "value-prop-read_only"; + String propertyValueTrue = "TRUE"; + String propertyNameFalse = "value-prop-delete_on_termination"; + String propertyValueFalse = "FALSE"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit simple properties values and save from a dialog + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.selectBooleanPropertyValue(propertyNameTrue, propertyValueTrue); + PropertiesAssignmentPage.selectBooleanPropertyValue(propertyNameFalse, propertyValueFalse); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that properties values are saved + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validateBooleanPropertyValue(propertyNameTrue, propertyValueTrue); + PropertiesAssignmentVerificator.validateBooleanPropertyValue(propertyNameFalse, propertyValueFalse); + } + + @Test + public void editAndSavePopupPropertyValueTest() throws Exception { +// Internal bug 391466 +// Popup Property: value editing is done in a popup text field, opened by clicking Edit button +// Example: subnetpoolid property + + String csarTestFile = csarFile1; + String componentName = "abstract_cif"; + String propertyName = "port_cif_imsli_port_subnetpoolid"; + String propertyValue = "updated by designer"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType( + "ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit popup property value and save + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnEditButton(propertyName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), propertyValue); + PropertiesAssignmentPage.clickOnSetButton(); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that popup property value is saved + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnEditButton(propertyName); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), propertyValue); + + } + + + @Test + public void editAndDiscardSimplePropertyValueTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_psm"; + String propertyNameString = "value-prop-nfc_function"; + String propertyNameInt = "value-prop-index_value"; + String propertyValueString = "abc"; + String propertyValueInt = "123"; + String propertyOrigValueString = ""; + String propertyOrigValueInt = "0"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit simple properties values and discard changes + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.editPropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentPage.editPropertyValue(propertyNameInt, propertyValueInt); + PropertiesAssignmentPage.clickOnDiscardButton(); + + //Verify that properties values are not saved + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameString, propertyOrigValueString); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameInt, propertyOrigValueInt); + } + + @Test + public void editAndSaveSimplePropertyFromDialogTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_psm"; + String propertyNameString = "value-prop-nfc_function"; + String propertyNameInt = "value-prop-index_value"; + String propertyValueString = "abc"; + String propertyValueInt = "123"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit simple properties values and save from a dialog + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.editPropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentPage.editPropertyValue(propertyNameInt, propertyValueInt); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.clickOnDialogCancelButton(); + + //Verify that properties values are not removed + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameInt, propertyValueInt); + + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.clickOnDialogSaveButton(); + + //Verify that properties values are saved + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameInt, propertyValueInt); + } + + + @Test + public void editAndDiscardSimplePropertyFromDialogTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_psm"; + String propertyNameString = "value-prop-nfc_function"; + String propertyNameInt = "value-prop-index_value"; + String propertyValueString = "abc"; + String propertyValueInt = "123"; + String propertyOrigValueString = ""; + String propertyOrigValueInt = "0"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit simple properties values and save from a dialog + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.editPropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentPage.editPropertyValue(propertyNameInt, propertyValueInt); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.clickOnDialogCancelButton(); + + ///Verify that properties values are not removed + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameInt, propertyValueInt); + + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.clickOnDialogDiscardButton(); + + //Verify that properties values are saved + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameString, propertyOrigValueString); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameInt, propertyOrigValueInt); + } + + + @Test + public void editAndSaveInputValueTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_psm"; + String propertyNameString = "value-input-nf_type"; + String propertyNameFloat = "value-input-pcm_volume_size_0"; + String propertyNameBoolean = "value-input-multi_stage_design"; + String propertyValueString = "POLICY"; + String propertyValueFloat = "80.1"; + String propertyValueBoolean = "TRUE"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen - Inputs + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnInputTab(); + + //Verify that Save button is disabled when inserting invalid value into Input field + PropertiesAssignmentPage.editPropertyValue(propertyNameFloat, propertyValueString); + AssertJUnit.assertTrue(PropertiesAssignmentPage.isButtonDisabled(DataTestIdEnum.PropertiesAssignmentScreen.SAVE_BUTTON.getValue())); + + //Insert valid values for different Input types and save + PropertiesAssignmentPage.editPropertyValue(propertyNameFloat, propertyValueFloat); + PropertiesAssignmentPage.editPropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentPage.selectBooleanPropertyValue(propertyNameBoolean, propertyValueBoolean); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that input values are saved after changing VF version + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameString, propertyValueString); + PropertiesAssignmentVerificator.validatePropertyValue(propertyNameFloat, propertyValueFloat); + PropertiesAssignmentVerificator.validateBooleanPropertyValue(propertyNameBoolean, propertyValueBoolean); + } + + //VF - List and Map Properties Tests + + @Test + public void editAndSaveListPropertyValueTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_pps"; + String propertyName = "compute_pps_user_data_format"; + String propertyListValueZero = "RAW"; + String propertyListValueOne = "property-value-one"; + String propertyListValueTwo = "property-value-two"; + + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit "list of strings" properties values and save + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnAddValueToList(propertyName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIndexedField(propertyName, 1), propertyListValueOne); + PropertiesAssignmentPage.clickOnAddValueToList(propertyName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIndexedField(propertyName, 2), propertyListValueTwo); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickODeleteValueFromList(propertyName, 1); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that properties values are saved + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildIndexedField(propertyName, 0), propertyListValueZero); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildIndexedField(propertyName, 1), propertyListValueTwo); + + + //Declare property as input, delete input + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.clickOnDeclareButton(); + AssertJUnit.assertTrue(PropertiesAssignmentPage.isPropertyChecked(propertyName)); + + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.findInput(componentName, propertyName); + PropertiesAssignmentPage.clickOnDeleteInputButton(); + PropertiesAssignmentPage.clickOnDeleteInputDialogConfirmationButton(); + PropertiesAssignmentPage.clickOnPropertiesTab(); + PropertiesAssignmentPage.findProperty(propertyName); + AssertJUnit.assertFalse(PropertiesAssignmentPage.isPropertyChecked(propertyName)); + } + + @Test + public void editAndSaveListOfComplexPropertyValueTest() throws Exception { + + //External Defect 437285 - PLEASE DON'T DELETE THE TEST!!!! + + String csarTestFile = csarFile1; + String componentName = "abstract_cdi"; + String propertyName = "port_cdi_imscore_port_ip_requirements"; + String nestedPropertyName = "ip_count"; + String propertyListValue = "12345"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit "list of strings" properties values and save + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnAddValueToList(propertyName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIComplexListField(propertyName, nestedPropertyName, 1), propertyListValue); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnExpandButton(propertyName, 1); + PropertiesAssignmentPage.deletePropertyValue(PropertyNameBuilder.buildIComplexListField(propertyName, nestedPropertyName, 1)); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that properties values are saved + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnExpandButton(propertyName, 1); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildIComplexListField(propertyName, nestedPropertyName, 1), ""); + + + } + + + @Test + public void editAndSaveMapPropertyValueTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "oam_volume_0"; + String propertyName = "metadata"; + String propertyMapKeyOne = "KEY1"; + String propertyMapValueOne = "property-value-one"; + String propertyMapKeyTwo = "KEY2"; + String propertyMapValueTwo = "property-value-two"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit "map of strings" properties values and save + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnAddValueToList(propertyName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIndexedField(propertyName, 0), propertyMapValueOne); + + + //Verify that Save and Declare buttons are disabled when leaving Key value empty + AssertJUnit.assertTrue(PropertiesAssignmentPage.isButtonDisabled(DataTestIdEnum.PropertiesAssignmentScreen.SAVE_BUTTON.getValue())); + AssertJUnit.assertTrue(PropertiesAssignmentPage.isButtonDisabled(DataTestIdEnum.PropertiesAssignmentScreen.DECLARE_BUTTON.getValue())); + + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIndexedKeyField(propertyName, 0), propertyMapKeyOne); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnAddValueToList(propertyName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIndexedKeyField(propertyName, 1), propertyMapKeyTwo); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIndexedField(propertyName, 1), propertyMapValueTwo); + PropertiesAssignmentPage.clickODeleteValueFromList(propertyName, 0); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that properties values are saved + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildIndexedKeyField(propertyName, 0), propertyMapKeyTwo); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildIndexedField(propertyName, 0), propertyMapValueTwo); + + //Declare property as input, delete input + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.clickOnDeclareButton(); + AssertJUnit.assertTrue(PropertiesAssignmentPage.isPropertyChecked(propertyName)); + + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.findInput(componentName, propertyName); + PropertiesAssignmentPage.clickOnDeleteInputButton(); + PropertiesAssignmentPage.clickOnDeleteInputDialogConfirmationButton(); + PropertiesAssignmentPage.clickOnPropertiesTab(); + PropertiesAssignmentPage.findProperty(propertyName); + AssertJUnit.assertFalse(PropertiesAssignmentPage.isPropertyChecked(propertyName)); + } + + + //VF - Complex Properties Tests + @Test + public void editAndSaveComplexPropertyValueTest() throws Exception { + + String csarTestFile = csarFile; + String componentName = "abstract_psm"; + String propertyName = "service_template_filter"; + String propertyNameString = "substitute_service_template"; + String propertyNameInt = "index_value"; + String propertyNameBoolean = "scaling_enabled"; + String propertyValueString = "Modified_psmServiceTemplate.yaml"; + String propertyValueInt = "2147483647"; + String propertyValueBoolean = "FALSE"; + + //Create VF + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + //Navigate to Properties Assignment screen, edit simple properties values and save + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIComplexField(propertyName, propertyNameString), propertyValueString); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildIComplexField(propertyName, propertyNameInt), propertyValueInt); + PropertiesAssignmentPage.selectBooleanPropertyValue(PropertyNameBuilder.buildIComplexField(propertyName, propertyNameBoolean), propertyValueBoolean); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Verify that properties values are saved + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildIComplexField(propertyName, propertyNameString), propertyValueString); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildIComplexField(propertyName, propertyNameInt), propertyValueInt); + PropertiesAssignmentVerificator.validateBooleanPropertyValue(PropertyNameBuilder.buildIComplexField(propertyName, propertyNameBoolean), propertyValueBoolean); + + //Select complex property and declare as input + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), PropertyNameBuilder.buildVfDeclaredPropValue(componentName, propertyName)); + } + + + //VF - Filter Tests + @Test + public void filterAllVfTest() throws Exception { + final int propertiesCountFilter = 22; + int propertiesCountWithoutFilter; + + String csarTestFile = csarFile; + String propertyName = "name"; + String propertyLocation = DataTestIdEnum.PropertiesAssignmentScreen.PROPERTY_NAME_COLUMN.getValue(); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarTestFile, getUser()); + + + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + //Count current properties number before filter is applied + propertiesCountWithoutFilter = GeneralUIUtils.getWebElementsListByContainsClassName(propertyLocation).size(); + PropertiesAssignmentPage.clickOnFilterButton(); + PropertiesAssignmentPage.clickOnFilterAllCheckbox(); + PropertiesAssignmentPage.findFilterBoxAndClick(propertyName); + PropertiesAssignmentPage.clickOnFilterApplyButton(); + PropertiesAssignmentVerificator.validateFilteredPropertiesCount(propertiesCountFilter, propertyLocation); + + PropertiesAssignmentPage.clickOnFilterClearAllButton(); + PropertiesAssignmentVerificator.validateFilteredPropertiesCount(propertiesCountWithoutFilter, propertyLocation); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow.java new file mode 100644 index 0000000000..c5bcd7b6d7 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow.java @@ -0,0 +1,688 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.verificator.PropertiesAssignmentVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HeatParamNameBuilder; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesAssignmentPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertyNameBuilder; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.List; + +import static org.testng.Assert.assertTrue; + +public class PropertiesAssignmentUpdateFlow extends SetupCDTest { + + private static String filePath; + private static String origFile = "virc_fe_be.csar"; + private static String origFile1 = "virc.csar"; + protected User sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath(""); + } + + @BeforeMethod + public void beforeTest() { + System.out.println("File repository is : " + filePath); + } + + @DataProvider(name = "assetFilesInputs", parallel = false) + public Object[][] createDataInputs() { + return new Object[][]{ + {"editInputValueTopChange.csar", ""}, + {"editInputValueNoTopChange.csar", "Updated-SRE-Mgt"}}; + } + + /** + * Topoplogy change in updated file - designer changes in inputs values are not kept after update + * No topoplogy change in updated file - designer changes in inputs values are kept after update + * + * @param updFileName - csar for update + * @param validationValue - expected property value after update + * @throws Exception + */ + @Test(dataProvider = "assetFilesInputs") + public void updateInputDefaultValueTest(String updFileName, String validationValue) throws Exception { + setLog(updFileName); + + String origTestFile = origFile; + String componentName = "abstract_virc_fe_be_0"; + String inputName = "management_net_name"; + String inputUpdValue = "Updated-SRE-Mgt"; + + //Import csar + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, origTestFile, getUser()); + + //Edit Input value + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildInputField(inputName), inputUpdValue); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Certify VF via API + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + + HomePage.navigateToHomePage(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + + //Update VF + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + GeneralPageElements.clickCheckoutButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file")); + ResourceUIUtils.updateVfWithCsar(filePath, updFileName); + + //Validate Input value - 1) empty in case of topology change; 2) user value is kept if no topology change + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), validationValue); + + } + + + @DataProvider(name = "assetFilesProperties", parallel = false) + public Object[][] createDataProp() { + return new Object[][]{ + {"editedPropValueToEmpty.csar", "value-prop-vm_type_tag", "updated_by_designer"}, + {"newPropValueToEmpty.csar", "value-prop-high_availablity", "updated_by_designer"}, + {"editedPropValueToNew.csar", "value-prop-vm_type_tag", "updated_by_file"}, + {"editedPropValueToEmptyTopChange.csar", "value-prop-vm_type_tag", ""}, + {"newPropValueToEmptyTopChange.csar", "value-prop-high_availablity", ""}, + {"editedPropValueToNewTopChange.csar", "value-prop-vm_type_tag", "updated_by_file"}}; + + } + + /** + * No topoplogy change in updated file - designer changes in properties values are kept after update + * OrigFile Designer UpdFile Result After Update + * --------------------------------------------------------------- + * prop1=value1 prop1=value2 prop1=null prop1=value2 + * prop1=null prop1=value1 prop1=null prop1=value1 + * prop1=value1 prop1=value2 prop1=value3 prop1=value3 + * + * + * Topoplogy change in updated file - designer changes in properties values are not kept after update + * OrigFile Designer UpdFile Result After Update + * --------------------------------------------------------------- + * prop1=value1 prop1=value2 prop1=null prop1=null + * prop1=null prop1=value1 prop1=null prop1=null + * prop1=value1 prop1=value2 prop1=value3 prop1=value3 + * + * @param updFileName - csar for update + * @param propertyName + * @param validationValue - expected property value after update + * @throws Exception + */ + @Test(dataProvider = "assetFilesProperties") + public void updatePropertyDefaultValueTest(String updFileName, String propertyName, String validationValue) throws Exception { + setLog(updFileName); + String origTestFile = origFile; + String componentName = "abstract_virc_fe_be_0"; + String propertyUpdValue = "updated_by_designer"; + + //Import csar + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, origTestFile, getUser()); + + //Edit Input value + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.editPropertyValue(propertyName, propertyUpdValue); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Certify VF via API + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + + HomePage.navigateToHomePage(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + + //Update VF + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + GeneralPageElements.clickCheckoutButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file")); + ResourceUIUtils.updateVfWithCsar(filePath, updFileName); + + //Validate Input value + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(propertyName, validationValue); + } + + + @Test + public void updatePropertyChangeVfiVersionTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "virc_fe_be_volume_0"; + String propertyName = "disk_bus"; + String propertyValue = "added_by_designer"; + String propertyValueUpd = "updated_by_designer"; + String inputName = componentName + "_" + propertyName; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Edit Property Value and declare as input + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(resourceReqDetails.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), propertyValue); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), propertyValue); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF input in Service properties, declare it as service input + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName), propertyValue); + PropertiesAssignmentPage.findSearchBoxAndClick(inputName); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), + propertyValue + ); + + //Checkout VF, update input value and check in - v0.2 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(resourceReqDetails.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.editPropertyValue( + PropertyNameBuilder.buildDeclaredInputField(componentName, propertyName), + propertyValueUpd + ); +// PropertiesAssignmentPage.deletePropertyValue(PropertyNameBuilder.buildDeclaredInputField(componentName, propertyName)); + PropertiesAssignmentPage.clickOnSaveButton(); + ResourceGeneralPage.clickCheckinButton(resourceReqDetails.getName()); + + //Change resource version on service + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.2"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Validate that service contains property with "get_input" value and input with the updated value + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.isPropertyChecked(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServicePropertyValue(componentName, propertyName), + PropertyNameBuilder.buildServiceDeclaredPropertyValue(componentInstance, componentName, propertyName) + ); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), + propertyValueUpd + ); + } + + @Test + public void updateServicePropertyChangeVfiVersionTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "virc_fe_be_volume_0"; + String propertyName = "multi_stage_design"; + String propertyValueBoolean = "TRUE"; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, + UserRoleEnum.DESIGNER, true + ).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF input in Service properties, declare it as service input + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + String defaultPropertyValueBoolean = PropertiesAssignmentPage.selectBooleanPropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), propertyValueBoolean); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validateBooleanPropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldServiceLevel(componentInstance, propertyName), + propertyValueBoolean + ); + +// //Checkout VF and check in - v0.2 + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + +// //Change resource version on service + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.2"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + +// //Validate that service contains property with "get_input" value and input with the updated value + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), + PropertyNameBuilder.buildServiceDeclaredPropValueServiceLevel(componentInstance, propertyName)); + PropertiesAssignmentPage.isPropertyChecked(propertyName); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validateBooleanPropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldServiceLevel(componentInstance, propertyName), + StringUtils.isEmpty(defaultPropertyValueBoolean) ? propertyValueBoolean : defaultPropertyValueBoolean + ); + } + + @Test + public void deletePropertyChangeVfiVersionTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "abstract_virc_fe_be_1"; + String propertyNameProp1 = "max_instances"; //empty property + String propertyNameProp2 = "nfc_naming_code"; //non-empty property + String propertyNameProp3 = "min_instances"; //non-empty property + String propertyNameProp4 = "nf_type"; + String propertyValueProp2 = "virc_fe_be"; + String propertyValueProp3 = "0"; + String propertyValueUpd1 = "111"; + String propertyValueUpd2 = "updated_by_designer"; + String propertyValueUpd4 = "added_by_designer_on_service"; + String inputName1 = componentName + "_" + propertyNameProp1; + String inputName2 = componentName + "_" + propertyNameProp2; + String inputName3 = componentName + "_" + propertyNameProp3; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //VF - Declare properties as inputs + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(resourceReqDetails.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyNameProp1); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyNameProp2); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyNameProp3); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName1), ""); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName2), propertyValueProp2); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName3), propertyValueProp3); + + //Check in VF, create Service and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, + true + ).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF inputs in Service properties, add or edit properties values + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findSearchBoxAndClick(inputName1); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(inputName1), propertyValueUpd1); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(inputName2); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(inputName2), propertyValueUpd2); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(inputName3); + PropertiesAssignmentPage.deletePropertyValue(PropertyNameBuilder.buildSimpleField(inputName3)); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyNameProp4); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propertyNameProp4), propertyValueUpd4); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Checkout and check in VF, change VFi version on Service to 0.2 + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Service - Validate properties values + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName1), propertyValueUpd1); +// PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName2), propertyValueProp2); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName3), propertyValueProp3); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propertyNameProp4), propertyValueUpd4); + + //Service - Declare properties as inputs + PropertiesAssignmentPage.findSearchBoxAndClick(inputName1); + PropertiesAssignmentPage.clickOnDeclareButton(); +// PropertiesAssignmentPage.findSearchBoxAndClick(inputName2); +// PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(inputName3); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyNameProp4); + PropertiesAssignmentPage.clickOnDeclareButton(); + // TODO: 5/9/2018 Add validation for input values + + //VF - delete some declared inputs + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(resourceReqDetails.getName()); + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.findInput(componentName, propertyNameProp1); + PropertiesAssignmentPage.clickOnDeleteInputButton(); + PropertiesAssignmentPage.clickOnDeleteInputDialogConfirmationButton(); +//// PropertiesAssignmentPage.findInput(componentName, propertyNameProp2); +// PropertiesAssignmentPage.clickOnDeleteInputButton(); +// PropertiesAssignmentPage.clickOnDeleteInputDialogConfirmationButton(); + + //VF - check in VF, change VFi version on Service to 0.3 + ResourceGeneralPage.clickCheckinButton(resourceReqDetails.getName()); + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.3"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Service - Validate that deleted inputs are not found in Service properties, others are found + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findProperty(inputName1); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildSimpleField(inputName1))); +// PropertiesAssignmentPage.findProperty(inputName2); +// assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildSimpleField(inputName2))); + PropertiesAssignmentPage.findProperty(inputName3); + assertTrue(GeneralUIUtils.isElementVisibleByTestId(PropertyNameBuilder.buildSimpleField(inputName3))); + PropertiesAssignmentPage.findProperty(propertyNameProp4); + assertTrue(GeneralUIUtils.isElementVisibleByTestId(PropertyNameBuilder.buildSimpleField(propertyNameProp4))); + + //Service - Validate that Service inputs that were declared from deleted properties are not found + // - Validate that other inputs remain - Currently input of min_instances disappears - BUG 411833!!! + } + + @Test + public void updateVFCPropertyChangeVFCiVersionTest() throws Throwable { + ResourceReqDetails atomicResourceMetaData; + String prop1 = "network_role"; + String propValue1 = "added_value_1"; + String prop2 = "is_default"; + String propValue2 = "TRUE"; + + //Import VFC, certify VFC + String fileName = "importVFC_VFC23.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + String vfcName = atomicResourceMetaData.getName(); + ResourceGeneralPage.clickCheckinButton(vfcName); + + //Create VF + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + //Add VFCi to VF canvas + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(vfcName); + + //VF Properties Assignment - edit properties values and declare as input + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findSearchBoxAndClick(prop1); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(prop1), propValue1); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(prop2); + String propDefaultValue2 = PropertiesAssignmentPage.selectBooleanPropertyValue(PropertyNameBuilder.buildSimpleField(prop2), propValue2); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnDeclareButton(); + + //Check out and check in VFC - v0.2 + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfcName); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCheckinButton(vfcName); + + //Change VFCi version in VF + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "0.2"); + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "0.2"); + + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vfMetaData.getName(), "0.1"); + List<ComponentInstance> components = resource.getComponentInstances(); + String normalizedName = components.get(0).getNormalizedName(); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.clickOnInputTab(); + //Verify that input value of the declared property that is EMPTY by default hasn't changed +// PropertiesAssignmentVerificator.validateBooleanPropertyValue(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop2), propValue2); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop1), propValue1); + //Verify that input value of the declared property that is NOT EMPTY by default has been changed + PropertiesAssignmentVerificator.validateBooleanPropertyValue(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop2), + StringUtils.isEmpty(propDefaultValue2) ? propValue2 : propDefaultValue2); + + //Check out VFC - v0.3, delete a property, check in VFC + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfcName); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + PropertiesPage.clickDeletePropertyFromPopup(prop1); + PropertiesPage.clickDeletePropertyFromPopup(prop2); + ResourceGeneralPage.clickCheckinButton(vfcName); + + //Change VFCi version in VF + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "0.3"); + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "0.3"); + + //Verify that properties and inputs were removed + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findProperty(prop1); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildSimpleField(prop1))); + PropertiesAssignmentPage.findProperty(prop2); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildSimpleField(prop2))); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.findProperty(normalizedName + "_" + prop1); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop1))); + PropertiesAssignmentPage.findProperty(normalizedName + "_" + prop2); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop2))); + } + + @Test + public void updateHeatParamChangeVfiVersionTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String artifactName = "base_fe_be"; + String heatParamName = "availability_zone_0"; + String heatParamUpdValue = "Updated_ZoneA"; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, + UserRoleEnum.DESIGNER, true + ).left().value(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfElement = vfCanvasManager.createElementOnCanvas(resource.getName()); + + //Select VFi on canvas, open Deployment Artifacts tab + vfCanvasManager.clickOnCanvaElement(vfElement); + CompositionPage.showDeploymentArtifactTab(); + DeploymentArtifactPage.hoverArtifact(artifactName); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + DeploymentArtifactPage.editHeatParamValue(HeatParamNameBuilder.buildCurrentHeatParamValue(heatParamName), heatParamUpdValue); + DeploymentArtifactPage.clickSaveEnvParameters(); + + //Checkout and check in VF - v0.2 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + //Change VFi version on Service canvas - v0.2 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfElement, "0.2"); +// VfVerificator.verifyInstanceVersion(service, getUser(), resource.getName(), "0.2"); + + //Validate that edited heatparam value is kept + CompositionPage.showDeploymentArtifactTab(); + DeploymentArtifactPage.hoverArtifact(artifactName); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + PropertiesAssignmentVerificator.validatePropertyValue(HeatParamNameBuilder.buildCurrentHeatParamValue(heatParamName), heatParamUpdValue); + DeploymentArtifactPage.clickCloseEnvParameters(); + + //Check out VF, delete heatparam value, check in VF - v0.3 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(resource.getName()); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + DeploymentArtifactPage.clickOnDeleteHeatParamValue(heatParamName); + DeploymentArtifactPage.clickSaveEnvParameters(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + //Change VFi version on Service canvas - v0.3 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfElement, "0.3"); + + //Validate that edited heatparam value is kept, default value is empty + CompositionPage.showDeploymentArtifactTab(); + DeploymentArtifactPage.hoverArtifact(artifactName); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + PropertiesAssignmentVerificator.validatePropertyValue(HeatParamNameBuilder.buildCurrentHeatParamValue(heatParamName), heatParamUpdValue); + PropertiesAssignmentVerificator.validatePropertyValueIsNull(HeatParamNameBuilder.buildDefaultHeatParamValue(heatParamName)); + DeploymentArtifactPage.clickCloseEnvParameters(); + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} + + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow_New.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow_New.java new file mode 100644 index 0000000000..0fcb75759d --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/PropertiesAssignmentUpdateFlow_New.java @@ -0,0 +1,926 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.verificator.PropertiesAssignmentVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HeatParamNameBuilder; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesAssignmentPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertyNameBuilder; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.util.List; + +import static org.testng.Assert.assertTrue; + +public class PropertiesAssignmentUpdateFlow_New extends SetupCDTest { + + private static String filePath; + private static String origFile = "virc_fe_be.csar"; + private static String origFile1 = "virc.csar"; + private User sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath(""); + } + + @BeforeMethod + public void beforeTest() { + System.out.println("File repository is : " + filePath); +// SetupCDTest.getExtendTest().log(Status.INFO, "File repository is : " + filePath); + } + + //Update VSP tests - validating VF properties/inputs values after updating VF with a new VSP + @DataProvider(name = "assetFilesInputs", parallel = false) + public Object[][] createDataInputs() { + return new Object[][]{ + {"editInputValueTopChange.csar", ""}, + {"editInputValueNoTopChange.csar", "Updated-SRE-Mgt"}}; + } + + /** + * Topoplogy change in updated file - designer changes in inputs values are not kept after update + * No topoplogy change in updated file - designer changes in inputs values are kept after update + * + * @param updFileName - csar for update + * @param validationValue - expected property value after update + * @throws Exception + */ + @Test(dataProvider = "assetFilesInputs") + public void updateInputDefaultValueTest(String updFileName, String validationValue) throws Exception { + setLog(updFileName); + + String origTestFile = origFile; + String componentName = "abstract_virc_fe_be_0"; + String inputName = "management_net_name"; + String inputUpdValue = "Updated-SRE-Mgt"; + + //Import csar + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, origTestFile, getUser()); + + //Edit Input value + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildInputField(inputName), inputUpdValue); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Certify VF via API + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + + HomePage.navigateToHomePage(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + + //Update VF + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + GeneralPageElements.clickCheckoutButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file")); + ResourceUIUtils.updateVfWithCsar(filePath, updFileName); + + //Validate Input value - 1) empty in case of topology change; 2) user value is kept if no topology change + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), validationValue); + + } + + + @DataProvider(name = "assetFilesProperties", parallel = false) + public Object[][] createDataProp() { + return new Object[][]{ + {"editedPropValueToEmpty.csar", "value-prop-vm_type_tag", "updated_by_designer", "updated_by_designer", false}, //no topology change - simple + {"newPropValueToEmpty.csar", "value-prop-high_availablity", "updated_by_designer", "updated_by_designer", false}, + {"editedPropValueToNew.csar", "value-prop-vm_type_tag", "updated_by_designer", "updated_by_file", false}, + {"virc_fe_be.csar", "value-prop-vm_type_tag", "", "virc_fe_be", true}, + {"editedPropValueToEmptyTopChange.csar", "value-prop-vm_type_tag", "updated_by_designer", "", false}, //topology change - simple + {"newPropValueToEmptyTopChange.csar", "value-prop-high_availablity", "updated_by_designer", "", false}, + {"editedPropValueToNewTopChange.csar", "value-prop-vm_type_tag", "updated_by_designer", "updated_by_file", false}, + {"virc_fe_be.csar", "value-prop-port_virc_fe_be_data_1_port_mac_requirements.mac_range_plan", "updated_by_designer", "updated_by_designer", false}, //no topology change - complex + {"virc_fe_be.csar", "value-prop-service_template_filter.count", "12345", "1", false}, + {"virc_fe_be.csar", "value-prop-service_template_filter.substitute_service_template", "", "Nested_virc_fe_beServiceTemplate.yaml", true}}; + } + + /** + * No topology change in updated file - designer changes in properties values are kept after update + * OrigFile Designer UpdFile Result After Update + * --------------------------------------------------------------- + * prop1=value1 prop1=value2 prop1=null prop1=value2 + * prop1=null prop1=value1 prop1=null prop1=value1 + * prop1=value1 prop1=value2 prop1=value3 prop1=value3 + * prop1=value1 prop1=null prop1=value1 prop1=value1 + * + * + * Topoplogy change in updated file - designer changes in properties values are not kept after update + * OrigFile Designer UpdFile Result After Update + * --------------------------------------------------------------- + * prop1=value1 prop1=value2 prop1=null prop1=null + * prop1=null prop1=value1 prop1=null prop1=null + * prop1=value1 prop1=value2 prop1=value3 prop1=value3 + * + * + * No topology change in updated files - complex property value changes + * OrigFile Designer UpdFile Result After Update + * --------------------------------------------------------------- + * prop1=null prop1=value1 prop1=null prop1=value1 + * prop1=value1 prop1=value2 prop1=value1 prop1=value1 + * prop1=value1 prop1=null prop1=value1 prop1=value1 + * + * @param updFileName - csar for update + * @param propertyName + * @param validationValue - expected property value after update + * @throws Exception + */ + @Test(dataProvider = "assetFilesProperties") + public void updatePropertyDefaultValueTest(String updFileName, String propertyName, String updValue, String validationValue, boolean userDeletesValue) throws Exception { + setLog(updFileName); + String origTestFile = origFile; + String componentName = "abstract_virc_fe_be_0"; +// String propertyUpdValue = "updated_by_designer"; + + //Import csar + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, + ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, origTestFile, getUser()); + + //Edit or delete Input value + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + if (userDeletesValue) { + PropertiesAssignmentPage.deletePropertyValue(propertyName); + } else { + PropertiesAssignmentPage.editPropertyValue(propertyName, updValue); + } + PropertiesAssignmentPage.clickOnSaveButton(); + + //Certify VF via API + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //Update VF + HomePage.navigateToHomePage(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToGeneralScreen(); + GeneralPageElements.clickCheckoutButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating VF with new file")); + ResourceUIUtils.updateVfWithCsar(filePath, updFileName); + + //Validate Input value + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + PropertiesAssignmentVerificator.validatePropertyValue(propertyName, validationValue); + } + + + //ChangeVersion tests - validating service property values after changing VFi version on service + @DataProvider(name = "assetFilesServiceProperties", parallel = false) + public Object[][] createDataServiceProp() { + return new Object[][]{ + {"max_instances", "", "111", "111"}, //edit service prop value, update with original empty value, keep user value after update + {"nfc_naming_code", "virc_fe_be", "updated_by_designer", "virc_fe_be"}}; //edit service prop value, update with original value, set original value after update + } + + @Test(dataProvider = "assetFilesServiceProperties") + public void changeVfiVersionServicePropertyEditValueTest(String propertyName, String origValue, String updValue, String expectedValue) throws Throwable { + setLog(propertyName); + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "abstract_virc_fe_be_1"; + String inputName = componentName + "_" + propertyName; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //VF - Declare property as input + declarePropertyAsInput(propertyName, componentName, resourceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), origValue); + + //Check in VF, create Service and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF inputs in Service properties, add or edit properties values + findServiceProperty(inputName, serviceReqDetails); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(inputName), updValue); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Checkout and check in VF, change VFi version on Service to 0.2 + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Service - Validate properties values + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName), expectedValue); + } + + + @Test + public void changeVfiVersionServicePropertyDeleteValueTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "abstract_virc_fe_be_1"; + String propertyName = "min_instances"; + String propertyValue = "0"; + String inputName = componentName + "_" + propertyName; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //VF - Declare properties as inputs + declarePropertyAsInput(propertyName, componentName, resourceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), propertyValue); + + //Check in VF, create Service and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF inputs in Service properties, delete property value + findServiceProperty(inputName, serviceReqDetails); + PropertiesAssignmentPage.deletePropertyValue(PropertyNameBuilder.buildSimpleField(inputName)); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Checkout and check in VF, change VFi version on Service to 0.2 + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Service - Validate properties values + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName), propertyValue); + } + + @Test + public void changeVfiVersionServiceGenericPropertyValueTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "abstract_virc_fe_be_1"; + String propertyName = "nf_type"; + String propertyUpdValue = "added by designer on service"; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Check in VF, create Service and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF inputs in Service properties, add or edit property value + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), propertyUpdValue); + PropertiesAssignmentPage.clickOnSaveButton(); + + //Checkout and check in VF, change VFi version on Service to 0.2 + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Service - Validate property value + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), propertyUpdValue); + } + + + //ChangeVersion tests - validating service input values after changing VFi version on service + @Test + public void changeVfiServiceInputEditValueTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "virc_fe_be_volume_0"; + String propertyName = "disk_bus"; + String propertyValue = "added_by_designer"; + String propertyValueUpd = "updated_by_designer"; + String inputName = componentName + "_" + propertyName; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Edit Property Value and declare as input + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + viewVfComponentProperties(componentName, resourceReqDetails); + editAndDeclareSimpleProperty(propertyName, propertyValue); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), propertyValue); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF input in Service properties, declare it as service input + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName), propertyValue); + findAndDeclareServiceProperty(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), propertyValue); + + //Checkout VF, update input value and check in - v0.2 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + viewVfInputs(resourceReqDetails); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildDeclaredInputField(componentName, propertyName), + propertyValueUpd); + PropertiesAssignmentPage.clickOnSaveButton(); + ResourceGeneralPage.clickCheckinButton(resourceReqDetails.getName()); + + //Change resource version on service + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.2"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Validate that service contains property with "get_input" value and input with the updated value + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.isPropertyChecked(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServicePropertyValue(componentName, propertyName), + PropertyNameBuilder.buildServiceDeclaredPropertyValue(componentInstance, componentName, propertyName)); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), propertyValueUpd); + } + + @Test + public void changeVfiServiceInputEditBooleanTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "virc_fe_be_volume_0"; + String propertyName = "multi_stage_design"; + String origValue = "FALSE"; + String updValue = "TRUE"; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF input in Service properties, declare it as service input + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.selectBooleanPropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), updValue); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validateBooleanPropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldServiceLevel(componentInstance, propertyName), + updValue); + +// //Checkout VF and check in - v0.2 + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + +// //Change resource version on service + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.2"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + +// //Validate that service contains property with "get_input" value and input with the updated value + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), + PropertyNameBuilder.buildServiceDeclaredPropValueServiceLevel(componentInstance, propertyName)); + PropertiesAssignmentPage.isPropertyChecked(propertyName); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validateBooleanPropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldServiceLevel(componentInstance, propertyName), + origValue); + } + + @Test + public void changeVfiServiceInputDeleteValueTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "abstract_virc_fe_be_0"; + String propertyName = "vm_type_tag"; + String propertyValue = "updated_by_designer"; + String inputName = componentName + "_" + propertyName; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Edit Property Value and declare as input + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + viewVfComponentProperties(componentName, resourceReqDetails); + editAndDeclareSimpleProperty(propertyName, propertyValue); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), propertyValue); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF input in Service properties, declare it as service input + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName), propertyValue); + findAndDeclareServiceProperty(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), propertyValue); + + //Checkout VF, update input value and check in - v0.2 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + viewVfInputs(resourceReqDetails); + PropertiesAssignmentPage.deletePropertyValue(PropertyNameBuilder.buildDeclaredInputField(componentName, propertyName)); + PropertiesAssignmentPage.clickOnSaveButton(); + ResourceGeneralPage.clickCheckinButton(resourceReqDetails.getName()); + + //Change resource version on service + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.2"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Validate that service contains property with "get_input" value and input with the updated value + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.isPropertyChecked(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServicePropertyValue(componentName, propertyName), + PropertyNameBuilder.buildServiceDeclaredPropertyValue(componentInstance, componentName, propertyName)); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), propertyValue); + } + + @Test + public void changeVfiServiceInputAddValueTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "virc_fe_be_volume_0"; + String propertyName = "disk_bus"; + String propertyValue = "updated_by_designer"; + String inputName = componentName + "_" + propertyName; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Edit Property Value and declare as input + declarePropertyAsInput(propertyName, componentName, resourceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), ""); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF input in Service properties, declare it as service input + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName), ""); + findAndDeclareServiceProperty(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), ""); + + //Checkout VF, update input value and check in - v0.2 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + viewVfInputs(resourceReqDetails); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildDeclaredInputField(componentName, propertyName), propertyValue); + PropertiesAssignmentPage.clickOnSaveButton(); + ResourceGeneralPage.clickCheckinButton(resourceReqDetails.getName()); + + //Change resource version on service + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.2"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Validate that service contains property with "get_input" value and input with the updated value + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.isPropertyChecked(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServicePropertyValue(componentName, propertyName), + PropertyNameBuilder.buildServiceDeclaredPropertyValue(componentInstance, componentName, propertyName)); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), propertyValue); + } + + @Test + public void changeVfiServiceInputDeleteInputTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String componentName = "virc_fe_be_volume_0"; + String propertyName = "disk_bus"; + String propertyValue = "added_by_designer"; + String inputName = componentName + "_" + propertyName; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Edit Property Value and declare as input + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + viewVfComponentProperties(componentName, resourceReqDetails); + editAndDeclareSimpleProperty(propertyName, propertyValue); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildInputField(inputName), propertyValue); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + + //Find the VF input in Service properties, declare it as service input + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(inputName), propertyValue); + findAndDeclareServiceProperty(inputName); + PropertiesAssignmentVerificator.validatePropertyValue( + PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName), propertyValue); + + //Checkout VF, delete input and check in - v0.2 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + viewVfInputs(resourceReqDetails); + PropertiesAssignmentPage.clickOnDeleteInputButton(); + PropertiesAssignmentPage.clickOnDeleteInputDialogConfirmationButton(); + ResourceGeneralPage.clickCheckinButton(resourceReqDetails.getName()); + + //Change resource version on service + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resource.getName(), "0.2"); + AtomicOperationUtils.changeComponentInstanceVersion(service, componentInstance, resource, UserRoleEnum.DESIGNER, true); + + //Validate that service property and input are deleted + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findProperty(inputName); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildSimpleField(inputName))); + PropertiesAssignmentPage.clickOnInputTab(); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildServiceDeclaredFieldVfLevel(componentInstance, componentName, propertyName))); + } + + + //ChangeVersion test - validating VF input values after changing VFCi version on VF + @Test + public void updateVFCPropertyChangeVFCiVersionTest() throws Throwable { + ResourceReqDetails atomicResourceMetaData; + String prop1 = "network_role"; + String propValue1 = "added_value_1"; + String prop2 = "is_default"; + String propValue2 = "TRUE"; + String propDefaultValue2 = "FALSE"; + + //Import VFC, certify VFC + String fileName = "importVFC_VFC23.yml"; + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + String vfcName = atomicResourceMetaData.getName(); + ResourceGeneralPage.clickCheckinButton(vfcName); + + //Create VF + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + //Add VFCi to VF canvas + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(vfcName); + + //VF Properties Assignment - edit properties values and declare as input + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findSearchBoxAndClick(prop1); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(prop1), propValue1); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(prop2); + PropertiesAssignmentPage.selectBooleanPropertyValue(PropertyNameBuilder.buildSimpleField(prop2), propValue2); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.clickOnDeclareButton(); + + //Check out and check in VFC - v0.2 + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfcName); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCheckinButton(vfcName); + + //Change VFCi version in VF + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "0.2"); + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "0.2"); + + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vfMetaData.getName(), "0.1"); + List<ComponentInstance> components = resource.getComponentInstances(); + String normalizedName = components.get(0).getNormalizedName(); + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.clickOnInputTab(); + //Verify that input value of the declared property that is EMPTY by default hasn't changed + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop1), propValue1); + //Verify that input value of the declared property that is NOT EMPTY by default has been changed + PropertiesAssignmentVerificator.validateBooleanPropertyValue(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop2), propDefaultValue2); + + //Check out VFC - v0.3, delete a property, check in VFC + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfcName); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + PropertiesPage.clickDeletePropertyFromPopup(prop1); + PropertiesPage.clickDeletePropertyFromPopup(prop2); + ResourceGeneralPage.clickCheckinButton(vfcName); + + //Change VFCi version in VF + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "0.3"); + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "0.3"); + + //Verify that properties and inputs were removed + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findProperty(prop1); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildSimpleField(prop1))); + PropertiesAssignmentPage.findProperty(prop2); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildSimpleField(prop2))); + PropertiesAssignmentPage.clickOnInputTab(); + PropertiesAssignmentPage.findProperty(normalizedName + "_" + prop1); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop1))); + PropertiesAssignmentPage.findProperty(normalizedName + "_" + prop2); + assertTrue(GeneralUIUtils.isElementInvisibleByTestId(PropertyNameBuilder.buildDeclaredInputField(normalizedName, prop2))); + } + + //ChangeVersion test - validating HEAT param values after changing VFi version on Service + @Test + public void updateHeatParamChangeVfiVersionTest() throws Throwable { + String vnfFile = "vIRC_FE_BE.zip"; + String artifactName = "base_fe_be"; + String heatParamName = "availability_zone_0"; + String heatParamUpdValue = "Updated_ZoneA"; + + //Import VSP, create VF - v0.1 + String filePath = FileHandling.getVnfRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + + //Check in VF and add VFi to Service + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + ServiceReqDetails serviceReqDetails = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service: " + serviceReqDetails.getName()); + org.openecomp.sdc.be.model.Service service = AtomicOperationUtils.createCustomService( + serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement vfElement = vfCanvasManager.createElementOnCanvas(resource.getName()); + + //Select VFi on canvas, open Deployment Artifacts tab + vfCanvasManager.clickOnCanvaElement(vfElement); + CompositionPage.showDeploymentArtifactTab(); + DeploymentArtifactPage.hoverArtifact(artifactName); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + DeploymentArtifactPage.editHeatParamValue(HeatParamNameBuilder.buildCurrentHeatParamValue(heatParamName), heatParamUpdValue); + DeploymentArtifactPage.clickSaveEnvParameters(); + + //Checkout and check in VF - v0.2 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + //Change VFi version on Service canvas - v0.2 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfElement, "0.2"); +// VfVerificator.verifyInstanceVersion(service, getUser(), resource.getName(), "0.2"); + + //Validate that edited heatparam value is kept + CompositionPage.showDeploymentArtifactTab(); + DeploymentArtifactPage.hoverArtifact(artifactName); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + PropertiesAssignmentVerificator.validatePropertyValue(HeatParamNameBuilder.buildCurrentHeatParamValue(heatParamName), heatParamUpdValue); + DeploymentArtifactPage.clickCloseEnvParameters(); + + //Check out VF, delete heatparam value, check in VF - v0.3 + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(resource.getName()); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + DeploymentArtifactPage.clickOnDeleteHeatParamValue(heatParamName); + DeploymentArtifactPage.clickSaveEnvParameters(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + //Change VFi version on Service canvas - v0.3 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfElement, "0.3"); + + //Validate that edited heatparam value is kept, default value is empty + CompositionPage.showDeploymentArtifactTab(); + DeploymentArtifactPage.hoverArtifact(artifactName); + DeploymentArtifactPage.clickEditEnvArtifact(artifactName); + PropertiesAssignmentVerificator.validatePropertyValue(HeatParamNameBuilder.buildCurrentHeatParamValue(heatParamName), heatParamUpdValue); + PropertiesAssignmentVerificator.validatePropertyValueIsNull(HeatParamNameBuilder.buildDefaultHeatParamValue(heatParamName)); + DeploymentArtifactPage.clickCloseEnvParameters(); + } + + + private void declarePropertyAsInput(String propertyName, String componentName, ResourceReqDetails resourceReqDetails) throws Exception { + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + viewVfComponentProperties(componentName, resourceReqDetails); + findAndDeclareServiceProperty(propertyName); + } + + private void viewServiceProperties(ServiceReqDetails serviceReqDetails) throws Exception { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(serviceReqDetails.getName()); + CompositionPage.moveToPropertiesScreen(); + } + + private void findServiceProperty(String inputName, ServiceReqDetails serviceReqDetails) throws Exception { + viewServiceProperties(serviceReqDetails); + PropertiesAssignmentPage.findSearchBoxAndClick(inputName); + } + + private void viewVfComponentProperties(String componentName, ResourceReqDetails resourceReqDetails) throws Exception { + GeneralUIUtils.findComponentAndClick(resourceReqDetails.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnComponentInComposition(componentName); + } + + private void findAndDeclareServiceProperty(String inputName) throws Exception { + PropertiesAssignmentPage.findSearchBoxAndClick(inputName); + PropertiesAssignmentPage.clickOnDeclareButton(); + PropertiesAssignmentPage.clickOnInputTab(); + } + + private void editAndDeclareSimpleProperty(String propertyName, String propertyValue) throws Exception { + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propertyName), propertyValue); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propertyName); + PropertiesAssignmentPage.clickOnDeclareButton(); + } + + private void viewVfInputs(ResourceReqDetails resourceReqDetails) throws Exception { + GeneralUIUtils.findComponentAndClick(resourceReqDetails.getName()); + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentPage.clickOnInputTab(); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} + + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Service.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Service.java new file mode 100644 index 0000000000..70bf7674fa --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Service.java @@ -0,0 +1,782 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ServiceCategoriesEnum; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.onap.sdc.frontend.ci.tests.verificator.DeploymentViewVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.InputsPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ServiceUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.TestException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.awt.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +public class Service extends SetupCDTest { + + private static final String DESCRIPTION = "kuku"; + private static final String ARTIFACT_LABEL = "artifact3"; + private static final String ARTIFACT_LABEL_UPDATE = "artifactUpdate"; + private static final String GET_ARTIFACT_LIST_BY_CLASS_NAME = "i-sdc-designer-sidebar-section-content-item-artifact"; + private static final String HEAT_FILE_YAML_NAME = "Heat-File.yaml"; + private static final String HEAT_FILE_YAML_UPDATE_NAME = "Heat-File-Update.yaml"; + private String filePath; + private static CanvasElement computeElement; + + public static CanvasElement getComputeElement() { + return computeElement; + } + + @BeforeMethod + public void beforeTest() { + filePath = FileHandling.getFilePath(""); + } + + + @Test + public void createService() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + } + + @Test + public void validDefaultContactAndTagAfterCreateService() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createServiceWithDefaultTagAndUserId(serviceMetadata, getUser()); + + assertTrue("wrong userId", getUser().getUserId().equals(ResourceGeneralPage.getContactIdText())); + + List<String> actualTags = Arrays.asList(ServiceGeneralPage.getTags()); + assertTrue("wrong tags", (actualTags.size() == 1) && actualTags.get(0).equals(serviceMetadata.getName())); + } + + @Test + public void validateHiddenCategories() throws Exception { + // Create Service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + // Get categories list + List<WebElement> ddOptions = ServiceGeneralPage.getCategories(); + + for (WebElement opt: ddOptions) { + assertFalse("Hidden Category visible", ServiceCategoriesEnum.PARTNERSERVICE.equals(opt.getText())); + } + + } + + @Test + public void updateService() throws Exception { + // Create Service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + // Update Service + ServiceGeneralPage.deleteOldTags(serviceMetadata); + serviceMetadata.setName(ElementFactory.getServicePrefix() + "UpdatedName" + serviceMetadata.getName()); + serviceMetadata.setDescription("updatedDescriptionSanity"); + serviceMetadata.setProjectCode("654321"); + serviceMetadata.setContactId("cs6543"); + serviceMetadata.getTags().addAll(Arrays.asList("updatedTag", "oneMoreUpdatedTag", "lastOne UpdatedTag")); + ServiceUIUtils.setServiceCategory(serviceMetadata, ServiceCategoriesEnum.VOIP); + ServiceUIUtils.fillServiceGeneralPage(serviceMetadata); + GeneralPageElements.clickCreateButton(); + + ServiceVerificator.verifyServiceUpdatedInUI(serviceMetadata); + } + + @Test + public void deleteService() throws Exception { + + // create service + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + // Delete service + //GeneralUIUtils.HighlightMyElement(GeneralUIUtils.getWebButton("delete_version")); + GeneralPageElements.clickTrashButtonAndConfirm(); + + // Verification + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CatalogUIUtilitis.catalogSearchBox(serviceMetadata.getName()); + ServiceVerificator.verifyServiceDeletedInUI(serviceMetadata); + } + + @Test + public void checkoutServiceTest() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, "OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GeneralPageElements.clickCheckoutButton(); + + serviceMetadata.setVersion("0.2"); + ServiceVerificator.verifyServiceLifecycle(serviceMetadata, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + ServiceVerificator.verifyVersionUI(serviceMetadata.getVersion()); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + serviceMetadata.setVersion("1.1"); + serviceMetadata.setUniqueId(null); + ServiceVerificator.verifyServiceLifecycle(serviceMetadata, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + ServiceVerificator.verifyVersionUI(serviceMetadata.getVersion()); + } + + @Test + public void submitServiceForTestingWithNonCertifiedAsset() throws Exception { + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.createVF(atomicResourceMetaData, getUser()); + //TODO Andrey changed to click on ceckIn button + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + try { + CompositionPage.clickSubmitForTestingButton(serviceMetadata.getName()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + assertTrue(errorMessage.contains(checkUIResponseOnError)); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + + } + + @Test + public void createLinkService() throws Exception { + String fileName2 = "vSeGW.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(resourceMetaData.getName()); + CanvasElement firstElement = canvasManager.createElementOnCanvas(resourceMetaData.getName()); + CanvasElement secondElement = canvasManager.createElementOnCanvas(resourceMetaData.getName()); + canvasManager.linkElements(firstElement, secondElement); + } + + @Test + public void addDeploymentArtifactInCompositionScreenTest() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, "OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + AssertJUnit.assertEquals(1, actualArtifactList.size()); + + for (WebElement actualArtifactFileName : CompositionPage.getAllAddedArtifacts()) { + assertTrue(HEAT_FILE_YAML_NAME.equals(actualArtifactFileName.getText())); + } + + } + + @Test + public void addInformationArtifactInCompositionScreenTest() throws Exception { + String descriptionText = DESCRIPTION; + List<String> artifactFileNames = new ArrayList<>(); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + ArtifactInfo artifactInfo = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, descriptionText, ARTIFACT_LABEL, "OTHER"); + CompositionPage.showInformationArtifactTab(); + List<WebElement> beforeArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifactInfo, CompositionPage.artifactPopup()); + + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + assertThat(actualArtifactList).as("Check number of artifacts").hasSize(beforeArtifactList.size() + 1); + int fileNameCounter = 0; + String fileName; + for (DataTestIdEnum.InformationalArtifactsService artifact : DataTestIdEnum.InformationalArtifactsService.values()) { + fileName = HEAT_FILE_YAML_NAME_PREFIX + fileNameCounter + HEAT_FILE_YAML_NAME_SUFFIX; + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(artifact, + FileHandling.getFilePath("uniqueFileNames"), fileName, descriptionText); + artifactFileNames.add(fileName); + fileNameCounter++; + } + artifactFileNames.add(HEAT_FILE_YAML_NAME); + int numberOfFiles = CompositionPage.getAllAddedArtifacts().size(); + assertThat(numberOfFiles).as("Check number of artifacts").isEqualTo(beforeArtifactList.size() + 1); + + fileNameCounter = 0; + for (WebElement actualArtifact : CompositionPage.getAllAddedArtifacts()) { + assertThat(actualArtifact.getText()).isEqualTo(artifactFileNames.get(fileNameCounter)); + fileNameCounter++; + } + } + + @Test + public void addAPIArtifactInCompositionScreenTest() throws Exception { + String fileName = HEAT_FILE_YAML_NAME, + descriptionText = DESCRIPTION, + url = "http://kuku.com"; + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + new ArtifactInfo(filePath, fileName, descriptionText, ARTIFACT_LABEL, "OTHER"); + CompositionPage.showAPIArtifactTab(); + + for (DataTestIdEnum.APIArtifactsService artifact : DataTestIdEnum.APIArtifactsService.values()) { + ArtifactUIUtils.fillPlaceHolderAPIArtifact(artifact, filePath, fileName, descriptionText, url); + } + int numberOfFiles = CompositionPage.getAllAddedArtifacts().size(), + numberOfPlacehoders = DataTestIdEnum.APIArtifactsService.values().length; + assertTrue(String.format("Wrong file count, should be %s files", numberOfPlacehoders), numberOfPlacehoders == numberOfFiles); + + for (WebElement actualArtifactFileName : CompositionPage.getAllAddedArtifacts()) { + assertTrue(fileName.equals(actualArtifactFileName.getText())); + } + } + + @Test + public void ManagmentWorkflowTest() throws Exception { + String descriptionText = DESCRIPTION, + descriptionTextEdit = "kuku2"; + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ServiceGeneralPage.getServiceLeftMenu().moveToManagmentWorkflow(); + ServiceGeneralPage.fillAndAddNewWorkflow(descriptionText, descriptionText); + ServiceVerificator.verifyManagmentWorkflow(descriptionText, descriptionText); + + ServiceGeneralPage.clickAddWorkflow(); + ServiceGeneralPage.fillAndAddNewWorkflow(descriptionTextEdit, descriptionTextEdit); + } + + @Test + public void deleteChangeVersionTest() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, "OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GeneralPageElements.clickCheckoutButton(); + + changeDeleteAndValidateVersionOnGeneralPage("0.1", "0.2", serviceMetadata.getName()); + + GeneralPageElements.clickCheckoutButton(); + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + changeDeleteAndValidateVersionOnGeneralPage("1.0", "1.1", serviceMetadata.getName()); + } + + @Test + public void compositionScreenRightSideButtonsTest() throws Exception { + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showInformationTab(); + ServiceVerificator.verifyOpenTabTitle(DataTestIdEnum.CompositionScreenEnum.INFORMATION); + + //feature removed from UI +// CompositionPage.showCompositionTab(); +// ServiceVerificator.verifyOpenTabTitle(CompositionScreenEnum.COMPOSITION); + + CompositionPage.showDeploymentArtifactTab(); + ServiceVerificator.verifyOpenTabTitle(DataTestIdEnum.CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB); + + CompositionPage.showInputsTab(); + assertTrue(CompositionPage.getOpenTabTitle().size() == 0); + + CompositionPage.showAPIArtifactTab(); + ServiceVerificator.verifyOpenTabTitle(DataTestIdEnum.CompositionScreenEnum.API); + + CompositionPage.showInformationArtifactTab(); + ServiceVerificator.verifyOpenTabTitle(DataTestIdEnum.CompositionScreenEnum.INFORMATION_ARTIFACTS); + + } + + @Test + public void addDeploymentArtifactToVFInstanceTest() throws Exception { + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, ArtifactTypeEnum.SNMP_POLL.getType()); + + CanvasElement computeElement = createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + checkInService(serviceMetadata); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + } + + @Test + public void deleteDeploymentArtifactFromVFInstanceTest() throws Exception { + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, ArtifactTypeEnum.SNMP_POLL.getType()); + + createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + deleteAndVerifyArtifact(actualArtifactList); + + } + + @Test + public void deleteDeploymentArtifactFromVFInstanceNextVersionTest() throws Exception { + +// if(true){ +// throw new SkipException("Open bug 342260"); +// } + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, ArtifactTypeEnum.SNMP_POLL.getType()); + + CanvasElement computeElement = createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + checkInService(serviceMetadata); + ResourceGeneralPage.clickCheckoutButton(); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + deleteAndVerifyArtifact(actualArtifactList); +// change container version + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()); + GeneralPageElements.selectVersion("V0.1"); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + + } + + // service version V0.1 default artifact, service version V0.2 updated artifact + @Test + public void updateDeploymentArtifactOnVFInstanceNextVersionTest() throws Exception { + +// if(true){ +// throw new SkipException("Open bug 322930"); +// } + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ArtifactInfo artifact = new ArtifactInfo(filePath, HEAT_FILE_YAML_NAME, DESCRIPTION, ARTIFACT_LABEL, ArtifactTypeEnum.SNMP_POLL.getType()); + ArtifactInfo artifactUpdate = new ArtifactInfo(filePath, HEAT_FILE_YAML_UPDATE_NAME, DESCRIPTION, ARTIFACT_LABEL_UPDATE, ArtifactTypeEnum.DCAE_INVENTORY_DOC.getType()); + + CanvasElement computeElement = createServiceWithRiArtifact(atomicResourceMetaData, serviceMetadata, artifact); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + checkInService(serviceMetadata); + ResourceGeneralPage.clickCheckoutButton(); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + deleteAndVerifyArtifact(actualArtifactList); +// upload new artifact + addDeploymentArtifact(artifactUpdate, CanvasManager.getCanvasManager(), computeElement); + checkArtifactIfAdded(1, HEAT_FILE_YAML_UPDATE_NAME); +// change container version + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()); + GeneralPageElements.selectVersion("V0.1"); + clickOncanvasElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + checkArtifactIfAdded(1, HEAT_FILE_YAML_NAME); + + } + + public void clickOncanvasElement(CanvasElement computeElement) { + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + canvasManager.clickOnCanvaElement(computeElement); + } + + public void checkInService(ServiceReqDetails serviceMetadata) throws Exception { + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + } + + public static void deleteAndVerifyArtifact(List<WebElement> actualArtifactList) { + if (actualArtifactList.size() > 0) { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ITEM.getValue() + ARTIFACT_LABEL); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to delete " + HEAT_FILE_YAML_NAME + " artifact" + " and check if deleted"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + ARTIFACT_LABEL); + GeneralPageElements.clickOKButton(); + assertTrue("Artifact does not deleted", !GeneralUIUtils.waitForElementInVisibilityByTestId(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME))); + } + } + + + public void checkArtifactIfAdded(Integer expectedNumOfARtifacts, String expectedArtifactName) { + + List<WebElement> actualArtifactList; + actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className(GET_ARTIFACT_LIST_BY_CLASS_NAME)); + assertTrue("Expected artifact count is: " + expectedNumOfARtifacts + ", but was " + actualArtifactList.size(), expectedNumOfARtifacts == actualArtifactList.size()); + + if (expectedNumOfARtifacts != 0) { + for (WebElement actualArtifactFileName : CompositionPage.getAllAddedArtifacts()) { + assertTrue("Artifact name does not match, expected " + expectedArtifactName + ", but was " + actualArtifactFileName.getText(), expectedArtifactName.equals(actualArtifactFileName.getText())); + } + } + + } + + + public CanvasElement createServiceWithRiArtifact(ResourceReqDetails atomicResourceMetaData, ServiceReqDetails serviceMetadata, ArtifactInfo artifact) throws Exception, AWTException { + ResourceUIUtils.createVF(atomicResourceMetaData, getUser()); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(atomicResourceMetaData.getName()); + + ServiceUIUtils.createService(serviceMetadata); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement computeElement = canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + addDeploymentArtifact(artifact, canvasManager, computeElement); + + return computeElement; + } + + + public void addDeploymentArtifact(ArtifactInfo artifact, CanvasManager canvasManager, CanvasElement computeElement) throws Exception { + canvasManager.clickOnCanvaElement(computeElement); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + } + + @Test + public void isDisabledAndReadOnlyInCheckin() throws Exception { + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + GeneralPageElements.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + + DataTestIdEnum.ServiceMetadataEnum[] fieldsForCheck = {DataTestIdEnum.ServiceMetadataEnum.SERVICE_NAME, + DataTestIdEnum.ServiceMetadataEnum.CONTACT_ID, + DataTestIdEnum.ServiceMetadataEnum.DESCRIPTION, + DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE, + DataTestIdEnum.ServiceMetadataEnum.TAGS}; + for (DataTestIdEnum.ServiceMetadataEnum field : fieldsForCheck) { + assertTrue(GeneralUIUtils.isElementReadOnly(field.getValue())); + } + + assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.ServiceMetadataEnum.CATEGORY.getValue())); + assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue())); + } + + // future removed from ui + @Test(enabled = true) + public void inputsTest() throws Exception { + String fileName = "service_input_test_VF2.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + GeneralPageElements.clickCheckinButton(resourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + String selectedInstanceName = addResourceToServiceInCanvas(resourceMetaData); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToInputsScreen(); + + InputsPage.addInputToService(selectedInstanceName, "volume_id"); + InputsPage.deleteServiceInput(selectedInstanceName, "volume_id"); + + // Trying to find deleted service input + try { + InputsPage.getServiceInput(selectedInstanceName, "volume_id"); + assert (false); + } catch (TestException e) { + } + } + + @Test() + public void deploymentViewServiceTest() throws Exception { + + User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + String fileName2 = "vSeGWNew.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, resourceMetaData.getName(), "0.1"); + + // update group property max_vf_module_instances of VF Module to 100 + List<GroupDefinition> groups = resource.getGroups(); + for (GroupDefinition group : groups) { + if (group.getType().equals("org.openecomp.groups.VfModule")) { + for (PropertyDataDefinition property : group.getProperties()) { + if (property.getName().equals("max_vf_module_instances")) { +// property.setValue("100"); +// List<PropertyDataDefinition> propertyList = new ArrayList<>(); +// propertyList.add(property); +// todo pass to method correct object instaed of value for custom json + AtomicOperationUtils.updateGroupPropertyOnResource("100", resource, group.getUniqueId(), user, true); + break; + } + } + } + } + + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + addResourceToServiceInCanvas(resourceMetaData); + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + DeploymentArtifactPage.getLeftMenu().moveToDeploymentViewScreen(); + serviceMetadata.setVersion("0.1"); + List<WebElement> instanceRowsFromTable = GeneralUIUtils.getElementsByCSS("div[data-tests-id^='hierarchy-instance'] span[class^='expand-collapse-title-text']"); + for (WebElement instanceRow : instanceRowsFromTable) { + String instanceRowText = instanceRow.getText(); + List<WebElement> instanceModulesList = DeploymentPage.getInstanceModulesList(instanceRowText); + for (WebElement instanceModule : instanceModulesList) { + String instanceModuleText = instanceModule.getText(); + ResourceUIUtils.clickOnElementByText(instanceModuleText, "instance"); + ServiceVerificator.verifyDeploymentPageSubElements(instanceModuleText.split("\\.\\.")[2], new DeploymentViewVerificator(filePath + fileName2)); + ServiceVerificator.verifyDisabledServiceProperties(); + SetupCDTest.getExtendTest().log(Status.INFO, "Sent email to Edith Ronen, waiting for answer"); + String isBaseValue = ServiceVerificator.getVFModulePropertyValue(serviceMetadata, "isBase", instanceModuleText); + if (isBaseValue.equals("false")) { + ServiceVerificator.verifyEnabledServiceProperties(); + } + ResourceUIUtils.clickOnElementByText(instanceModuleText, "instance"); + } + } + } + + @Test + public void vfModuleCustomizationUUIDServiceTest() throws Exception { + String fileName2 = "vSeGW.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + ResourceGeneralPage.clickCheckinButton(resourceMetaData.getName()); + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + addResourceToServiceInCanvas(resourceMetaData); + + serviceMetadata.setVersion("0.1"); + ServiceVerificator.verifyVFModuleCustomizationUUID(serviceMetadata); + } + + @Test + public void checkoutCertifyRemainSameCustomizationUUIDServiceTest() throws Exception { + String fileName2 = "vSeGW.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName2, getUser()); + //TODO Andrey should click on certify button + ResourceGeneralPage.clickCertifyButton(resourceMetaData.getName()); + + /*reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(resourceMetaData.getName()); + TesterOperationPage.certifyComponent(resourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER);*/ + + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createService(serviceMetadata); + + addResourceToServiceInCanvas(resourceMetaData); + + serviceMetadata.setVersion("0.1"); + ServiceVerificator.verifyVFModuleCustomizationUUID(serviceMetadata); + List<String> allVFModuleCustomizationUUIDs = ServiceVerificator.getAllVFModuleCustomizationUUIDs(serviceMetadata); + + ResourceGeneralPage.clickCheckinButton(serviceMetadata.getName()); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + GeneralPageElements.clickCheckoutButton(); + + serviceMetadata.setVersion("0.2"); + assertTrue(ServiceVerificator.isEqualCustomizationUUIDsAfterChanges(allVFModuleCustomizationUUIDs, ServiceVerificator.getAllVFModuleCustomizationUUIDs(serviceMetadata))); + + ResourceGeneralPage.clickSubmitForTestingButton(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + TesterOperationPage.certifyComponent(serviceMetadata.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + serviceMetadata.setVersion("1.1"); + serviceMetadata.setUniqueId(null); + assertTrue(ServiceVerificator.isEqualCustomizationUUIDsAfterChanges(allVFModuleCustomizationUUIDs, ServiceVerificator.getAllVFModuleCustomizationUUIDs(serviceMetadata))); + } + + @Test + public void createServiceWithALaCarteInstanTypeAndCheckItsTosca() throws Exception { + getExtendTest().log(Status.INFO, "Starting the test: createServiceWithALaCarteInstanTypeAndCheckItsTosca."); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createServiceWithDefaultTagAndUserId(serviceMetadata, getUser()); + getExtendTest().log(Status.INFO, "Done creating service over the UI, " + + "about to move into Tosca Artifacts section."); + ResourceGeneralPage.moveToToscaArtifactsSectionAndDownloadTosca(); + getExtendTest().log(Status.INFO, "Downloaded Template YAML File."); + AssertJUnit.assertTrue(ServiceGeneralPage.parseToscaFileIntoServiceAndValidateProperties(serviceMetadata)); + getExtendTest().log(Status.INFO, "Test is successful."); + } + + @Test + public void createServiceWithALaCarteInstanTypeAndVerifyChosenValue() throws Exception { + getExtendTest().log(Status.INFO, "Starting the test: createServiceWithALaCarteInstanTypeAndVerifyChosenValue."); + ServiceReqDetails serviceMetadata = ElementFactory.getDefaultService(); + ServiceUIUtils.createServiceWithDefaultTagAndUserId(serviceMetadata, getUser()); + getExtendTest().log(Status.INFO, "Done creating service over the UI, " + + "about to move into Home page."); + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(serviceMetadata.getName()); + assertTrue(serviceMetadata.getInstantiationType().equals(ServiceGeneralPage.getInstantiationTypeChosenValue())); + } + + + public static synchronized String addResourceToServiceInCanvas(ResourceReqDetails resourceMetaData) throws Exception { + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + if (computeElement == null) { + computeElement = createCanvasElement(resourceMetaData); + } + CanvasManager.getCanvasManager().clickOnCanvaElement(computeElement); + return CompositionPage.getSelectedInstanceName(); + } + + private static synchronized CanvasElement createCanvasElement(ResourceReqDetails resourceMetaData) throws Exception { + CompositionPage.searchForElement(resourceMetaData.getName()); + return CanvasManager.getCanvasManager().createElementOnCanvas(resourceMetaData.getName()); + } + + public static void changeDeleteAndValidateVersionOnGeneralPage(String previousVersion, String currentVersion, String serviceName) throws Exception { + GeneralPageElements.selectVersion("V" + previousVersion); + ServiceVerificator.verifyVersionUI(previousVersion); + GeneralUIUtils.clickJSOnElementByText("latest version"); + ServiceVerificator.verifyVersionUI(currentVersion); + GeneralPageElements.clickTrashButtonAndConfirm(); + GeneralUIUtils.findComponentAndClick(serviceName); + ServiceVerificator.verifyVersionUI(previousVersion); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ToscaValidationTest.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ToscaValidationTest.java new file mode 100644 index 0000000000..6e684d60b4 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/ToscaValidationTest.java @@ -0,0 +1,945 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.onap.sdc.frontend.ci.tests.dataProvider.OnbordingDataProviders; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.tosca.model.ToscaMetadataFieldsPresentationEnum; +import org.onap.sdc.frontend.ci.tests.utilities.DownloadManager; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.backend.ci.tests.utils.CsarParserUtils; +import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.rest.ArtifactRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.PropertyRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser; +import org.onap.sdc.frontend.ci.tests.verificator.ToscaValidation; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.NodeTemplate; +import org.onap.sdc.toscaparser.api.elements.Metadata; +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; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.ComponentInstanceInput; +import org.openecomp.sdc.be.model.GroupDefinition; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.PropertyDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.backend.ci.tests.datatypes.GroupHeatMetaDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaGroupPropertyDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaInputsTopologyTemplateDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaServiceGroupsMetadataDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaTopologyTemplateDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.VfModuleDefinition; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +import static org.testng.Assert.assertFalse; + + +public class ToscaValidationTest extends SetupCDTest { + + private static final String GENERIC_VF = "Generic_VF"; + private static final String GENERIC_PNF = "Generic_PNF"; + private static final String GENERIC_CR = "Generic_CR"; + + protected SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + User user = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + + @Test(dataProviderClass = OnbordingDataProviders.class, dataProvider = "VNF_List") + public void toscaFileValidator(String filePath, String vnfFile) throws Exception { +//--------------------------GENERAL-------------------------------- +/*// for debugging only + setLog("Test"); + File amdocsCsarFileName = (new File("C:\\Users\\al714h\\Downloads\\d218be69637647b0b693647d84a8c03f.csar")); + toscaMainAmdocsDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(amdocsCsarFileName); + toscaMainVfDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File("C:\\Users\\al714h\\Downloads\\resource-Civfonboarded2016073VmxBv301072E2eE60f5c15-csar.csar")); + */ + // vnfFile = "vRouter for DHV Test_Version_4.zip"; + setLog(vnfFile); + List<Boolean> status = new ArrayList<>(); + ISdcCsarHelper fdntCsarHelper; + File filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory()); +//--------------------------AMDOCS-------------------------------- + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, user);//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + resourceReqDetails = createCustomizedVsp(resourceReqDetails, filePath, vnfFile); + ToscaDefinition toscaMainAmdocsDefinition = downloadAndGetToscaMainYamlObjectUI(resourceReqDetails, filesFolder); +//------adding generic inputs to expected object + toscaMainAmdocsDefinition = addGenericPropertiesToToscaDefinitionObject(toscaMainAmdocsDefinition, GENERIC_VF); +// copy object + ToscaDefinition toscaExpectedMainServiceDefinition = new ToscaDefinition(toscaMainAmdocsDefinition); +// create list of modules from HEAT.meta file + File latestFileFromDir = FileHandling.getLastModifiedFileNameFromDir(); + List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition = CsarParserUtils.getListTypeHeatMetaDefinition(latestFileFromDir); +//TODO VfModuleVerificator.verifyGroupMetadata(); +//TODO--------------------------AMDOCS DOWNLOAD VIA APIS-------------------------------- +//--------------------------VF-------------------------------- +// create VF base on VNF imported from previous step - have, resourceReqDetails object include part of resource metadata + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + ToscaDefinition toscaMainVfDefinition = downloadAndGetToscaMainYamlObjectApi(resource, filesFolder); +//--------------------------SERVICE-------------------------------- + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService();//getServiceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstanceDefinition = addComponentInstanceToComponentContainer.left().value(); +//--------------------------getProperties set values and declare-------------------- + Component componentObject = AtomicOperationUtils.getComponentObject(service, UserRoleEnum.DESIGNER); + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = componentObject.getComponentInstancesInputs(); + setValuesToPropertiesList(componentInstancesInputs, toscaExpectedMainServiceDefinition); + PropertyRestUtils.declareProporties(componentObject, componentInstancesInputs, user); + + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + Map<String, VfModuleDefinition> expectedVfModulesDefinitionObject = createExpectedVfModuleDefinitionObject(resource, service, listTypeHeatMetaDefinition); + + File serviceCsarFileName = new File(File.separator + "ServiceCsar_" + ElementFactory.generateUUIDforSufix() + ".csar"); + OnboardingUtillViaApis.downloadToscaCsarToDirectory(service, new File(filesFolder.getPath() + serviceCsarFileName)); + ToscaDefinition toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + serviceCsarFileName)); +//--------------------------initialization of Tosca Parser-------------------------------- + fdntCsarHelper = initSdcCsarHelper(serviceCsarFileName, filesFolder); +////---------------------------TESTS-------------------------------------------------- + validateVfModuleJsonFile(expectedVfModulesDefinitionObject, service, componentInstanceDefinition.getUniqueId(), vnfFile, status); + validateVfMetadata(toscaMainAmdocsDefinition, toscaMainVfDefinition, resourceReqDetails, resource, vnfFile, status); + validateResourceNodeTemplateMetadata(toscaMainVfDefinition, resource, vnfFile, status); + validateServiceMetadata(toscaMainServiceDefinition, serviceReqDetails, service, vnfFile, status); + validateServiceNodeTemplateMetadata(toscaMainServiceDefinition, componentInstanceDefinition, resourceReqDetails, resource, vnfFile, status); + validateServiceMetadataUsingParser(fdntCsarHelper, serviceReqDetails, service, vnfFile, status); + validateServiceNodeTemplateMetadataUsingParser(fdntCsarHelper, resourceReqDetails, resource, componentInstanceDefinition, vnfFile, status); + validateResourceInputs(toscaMainAmdocsDefinition, toscaMainVfDefinition, vnfFile, status); + validateServiceInputs(toscaExpectedMainServiceDefinition, toscaMainServiceDefinition, vnfFile, status); + validateServiceInputsUsingParser(fdntCsarHelper, toscaExpectedMainServiceDefinition, vnfFile, status); + + Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject = createExpectedToscaServiceGroupsDefinitionObject(resource, service, listTypeHeatMetaDefinition); + validateServiceModuleMetadata(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition, vnfFile, status); + validateServiceModuleProperty(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition, vnfFile, status); + validateServiceModuleMetadataUsingParser(fdntCsarHelper, expectedToscaServiceGroupsDefinitionObject, vnfFile, status); + validateServiceModulePropertyUsingParser(fdntCsarHelper, expectedToscaServiceGroupsDefinitionObject, vnfFile, status); + + if (status.contains(false)) { + SetupCDTest.getExtendTest().log(Status.FAIL, "Summary: tosca validation test failed with zip file " + vnfFile); + assertFalse(true); + } + } + + + @DataProvider(name = "toscaValidationTest", parallel = true) + public static Object[][] dataProviderForSpecificResourceType() { + return new Object[][]{ + {"networkModel", ResourceTypeEnum.PNF, GENERIC_PNF}, + {"collectorResourceModel", ResourceTypeEnum.CR, GENERIC_CR}, + }; + } + + @Test(dataProvider = "toscaValidationTest") + public void validateSpecificResourceType(String type, ResourceTypeEnum resourceType, String genericPropName) throws Exception { +//--------------------------GENERAL-------------------------------- + String vnfFile = type; + setLog(vnfFile); + List<Boolean> status = new ArrayList<>(); + ISdcCsarHelper fdntCsarHelper; + ToscaDefinition expectedToscaMainDefinition = new ToscaDefinition(); + File filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory()); +// filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory()); + + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(resourceType, user); + expectedToscaMainDefinition = addGenericPropertiesToToscaDefinitionObject(expectedToscaMainDefinition, genericPropName); + ToscaDefinition toscaExpectedMainServiceDefinition = new ToscaDefinition(expectedToscaMainDefinition); +//--------------------------VF-------------------------------- + Resource resource = AtomicOperationUtils.createResourceByResourceDetails(resourceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + ToscaDefinition toscaMainVfDefinition = downloadAndGetToscaMainYamlObjectApi(resource, filesFolder); + +//--------------------------SERVICE-------------------------------- + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstanceDefinition = addComponentInstanceToComponentContainer.left().value(); + +//--------------------------getProperties set values and declare-------------------- + + Component componentObject = AtomicOperationUtils.getComponentObject(service, UserRoleEnum.DESIGNER); + Map<String, List<ComponentInstanceInput>> componentInstancesInputs = componentObject.getComponentInstancesInputs(); + setValuesToPropertiesList(componentInstancesInputs, toscaExpectedMainServiceDefinition); + PropertyRestUtils.declareProporties(componentObject, componentInstancesInputs, user); + + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + File ServiceCsarFileName = new File(File.separator + "ServiceCsar_" + ElementFactory.generateUUIDforSufix() + ".csar"); + OnboardingUtillViaApis.downloadToscaCsarToDirectory(service, new File(filesFolder.getPath() + ServiceCsarFileName)); + ToscaDefinition toscaMainServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + ServiceCsarFileName)); + +//--------------------------initialization of Tosca Parser-------------------------------- + + fdntCsarHelper = initSdcCsarHelper(ServiceCsarFileName, filesFolder); + + +//---------------------------TESTS-------------------------------------------------- + validateVfMetadata(expectedToscaMainDefinition, toscaMainVfDefinition, resourceReqDetails, resource, vnfFile, status); + validateResourceNodeTemplateMetadata(toscaMainVfDefinition, resource, vnfFile, status); + validateServiceMetadata(toscaMainServiceDefinition, serviceReqDetails, service, vnfFile, status); + validateServiceNodeTemplateMetadata(toscaMainServiceDefinition, componentInstanceDefinition, resourceReqDetails, resource, vnfFile, status); + validateServiceMetadataUsingParser(fdntCsarHelper, serviceReqDetails, service, vnfFile, status); + validateServiceNodeTemplateMetadataUsingParser(fdntCsarHelper, resourceReqDetails, resource, componentInstanceDefinition, vnfFile, status); + validateResourceInputs(expectedToscaMainDefinition, toscaMainVfDefinition, vnfFile, status); + validateServiceInputs(toscaExpectedMainServiceDefinition, toscaMainServiceDefinition, vnfFile, status); + validateServiceInputsUsingParser(fdntCsarHelper, toscaExpectedMainServiceDefinition, vnfFile, status); + + if (status.contains(false)) { + SetupCDTest.getExtendTest().log(Status.FAIL, "Summary: tosca validation test failed with zip file " + vnfFile); + assertFalse(true); + } + } + + /** + * The method set values to toscaDefinition object service level only, to resource level should put instead of setDefault --> setValue + * inputs.get(componentInstanceInput.getName()).setValue(randomString); + * + * @param componentInstancesInputs list of componentInstancesInputs + * @param toscaDefinition + */ + private void setValuesToPropertiesList(Map<String, List<ComponentInstanceInput>> componentInstancesInputs, ToscaDefinition toscaDefinition) { + for (Map.Entry<String, List<ComponentInstanceInput>> entry : componentInstancesInputs.entrySet()) { + List<ComponentInstanceInput> value = entry.getValue(); + String[] names = entry.getKey().split("\\."); + String expectedServiceInputPrefix = null; + Map<String, ToscaInputsTopologyTemplateDefinition> inputs = toscaDefinition.getTopology_template().getInputs(); + if (names.length > 0) { + expectedServiceInputPrefix = names[names.length - 1] + "_"; + } + for (ComponentInstanceInput componentInstanceInput : value) { + + + String type = componentInstanceInput.getType(); + List<String> myList = new ArrayList<>(); + myList.add("cbf8049e-69e8-48c3-a06f-255634391403"); + switch (type) { + case "string": + String randomString = getRandomString(); + componentInstanceInput.setValue(randomString); + inputs.get(componentInstanceInput.getName()).setDefault(randomString); + + break; + case "integer": + int randomInteger = getRandomInteger(); + componentInstanceInput.setValue(Integer.toString(randomInteger)); + inputs.get(componentInstanceInput.getName()).setDefault(randomInteger); + break; + case "float": + componentInstanceInput.setValue("5.5"); + inputs.get(componentInstanceInput.getName()).setDefault("5.5"); + + break; + case "boolean": + componentInstanceInput.setValue("true"); + inputs.get(componentInstanceInput.getName()).setDefault("true"); + break; + case "list": + String myListofStrings = myList.toString(); + componentInstanceInput.setValue(myListofStrings); + inputs.get(componentInstanceInput.getName()).setDefault(myListofStrings); + break; + case "json": + String myJson = "{\"firstParam\":\"my First Param Value\",\"secondParam\":\"my Second Param Value\",\"numberParam\":666}"; + componentInstanceInput.setValue(myJson); + inputs.get(componentInstanceInput.getName()).setDefault(myJson); + break; + case "comma_delimited_list": + String commaDelimitedList = "[\"one\", \"two\"]"; + componentInstanceInput.setValue(commaDelimitedList); + inputs.get(componentInstanceInput.getName()).setDefault(commaDelimitedList); + break; + default: + break; + } + + String expectedServiceInputName = expectedServiceInputPrefix + componentInstanceInput.getName(); + ToscaInputsTopologyTemplateDefinition oldInput = inputs.get(componentInstanceInput.getName()); + inputs.put(expectedServiceInputName, oldInput); + inputs.remove(componentInstanceInput.getName()); + + } + + } + } + + protected String getRandomString() { + final int LengthOfRandomString = 18; + String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; + StringBuilder salt = new StringBuilder(); + Random rnd = new Random(); + while (salt.length() < LengthOfRandomString) { + int index = (int) (rnd.nextFloat() * SALTCHARS.length()); + salt.append(SALTCHARS.charAt(index)); + } + String strValue = salt.toString(); + return strValue; + + } + + protected int getRandomInteger() { + final int low = 10; + final int high = 100; + Random r = new Random(); + return r.nextInt(high - low) + low; + } + + + //--------------------------Metadata verification-------------------------------- +//--------------------------Resource-------------------------------- + + public List<Boolean> validateVfMetadata(ToscaDefinition toscaMainAmdocsDefinition, ToscaDefinition toscaMainVfDefinition, ResourceReqDetails resourceReqDetails, Resource resource, String vnfFile, List<Boolean> status) throws Exception { + reportStartTestPrint("validateVfMetadata", vnfFile); + //add resource metadata to expected object + toscaMainAmdocsDefinition = addAndGenerateResourceMetadataToExpectedObject(toscaMainAmdocsDefinition, resourceReqDetails, resource); + Either<Boolean, Map<String, Object>> resourceToscaMetadataValidator = ToscaValidation.resourceToscaMetadataValidator(toscaMainAmdocsDefinition, toscaMainVfDefinition); + if (resourceToscaMetadataValidator.isRight()) { + status.add(false); + } + return status; + } + + public List<Boolean> validateResourceNodeTemplateMetadata(ToscaDefinition toscaMainVfDefinition, Resource resource, String vnfFile, List<Boolean> status) throws Exception { + reportStartTestPrint("validateResourceNodeTemplateMetadata", vnfFile); + Map<String, Map<String, String>> generateReosurceNodeTemplateMetadataToExpectedObject = generateResourceNodeTemplateMetadataToExpectedObject(resource); + Boolean resourceToscaMetadataValidator = ToscaValidation.resourceToscaNodeTemplateMetadataValidator(generateReosurceNodeTemplateMetadataToExpectedObject, toscaMainVfDefinition); + if (!resourceToscaMetadataValidator) { + status.add(false); + } + return status; + } + + //--------------------------Service-------------------------------- + public List<Boolean> validateServiceMetadata(ToscaDefinition toscaMainServiceDefinition, ServiceReqDetails serviceReqDetails, Service service, String vnfFile, List<Boolean> status) throws Exception { + reportStartTestPrint("validateServiceMetadata", vnfFile); + Map<String, String> generateServiceMetadataToExpectedObject = generateServiceMetadataToExpectedObject(serviceReqDetails, service); + Either<Boolean, Map<String, Object>> serviceToscaMetadataValidator = ToscaValidation.serviceToscaMetadataValidator(generateServiceMetadataToExpectedObject, toscaMainServiceDefinition); + if (serviceToscaMetadataValidator.isRight()) { + status.add(false); + } + return status; + } + + + public List<Boolean> validateServiceNodeTemplateMetadata(ToscaDefinition toscaMainServiceDefinition, ComponentInstance componentInstanceDefinition, ResourceReqDetails resourceReqDetails, Resource resource, String vnfFile, List<Boolean> status) throws Exception { + reportStartTestPrint("validateServiceNodeTemplateMetadata", vnfFile); + Map<String, String> generateServiceNodeTemplateMetadataToExpectedObject = generateServiceNodeTemplateMetadataToExpectedObject(resourceReqDetails, resource, componentInstanceDefinition); + Either<Boolean, Map<String, Object>> serviceToscaMetadataValidator = ToscaValidation.componentToscaNodeTemplateMetadataValidator(generateServiceNodeTemplateMetadataToExpectedObject, toscaMainServiceDefinition, componentInstanceDefinition.getName(), ComponentTypeEnum.SERVICE, componentInstanceDefinition.getName()); + if (serviceToscaMetadataValidator.isRight()) { + status.add(false); + } + return status; + } + + private List<Boolean> validateVfModuleJsonFile(Map<String, VfModuleDefinition> expectedVfModulesDefinitionObject, Service service, String resInstUniqueId, String vnfFile, List<Boolean> status) throws Exception { + reportStartTestPrint("validateVfModuleJsonFile", vnfFile); + String artifactUniqueId = null; + for (ComponentInstance inst : service.getComponentInstances()) { + if (inst.getUniqueId().equals(resInstUniqueId)) { + artifactUniqueId = inst.getDeploymentArtifacts().get("vfModulesMetadata").getUniqueId(); + break; + } + } + if (artifactUniqueId == null) { + SetupCDTest.getExtendTest().log(Status.ERROR, "validateVfModuleJsonFile verification failed, artifact vfModulesMetadata not found"); + status.add(false); + return status; + } + RestResponse restResponse = ArtifactRestUtils.downloadResourceInstanceArtifact(service.getUniqueId(), resInstUniqueId, user, artifactUniqueId); + String artifactPayload = ArtifactRestUtils.getDecodedArtifactPayloadFromResponse(restResponse); + Map<String, VfModuleDefinition> actualVfModulesDefinitionObject = ResponseParser.convertVfModuleJsonResponseToJavaObject(artifactPayload); + Either<Boolean, Map<String, Object>> vfModuleJsonFileValidator = ToscaValidation.vfModuleJsonFileValidator(expectedVfModulesDefinitionObject, actualVfModulesDefinitionObject); + if (vfModuleJsonFileValidator.isRight()) { + status.add(false); + } + return status; + } + + //--------------------------Service verification against Pavel Parser-------------------------------- + public List<Boolean> validateServiceMetadataUsingParser(ISdcCsarHelper fdntCsarHelper, ServiceReqDetails serviceReqDetails, Service service, String vnfFile, List<Boolean> status) throws Exception { + if (fdntCsarHelper == null) { + reportSkipTestPrint("validateServiceMetadataUsingParser", status); + } else { + reportStartTestPrint("validateServiceMetadataUsingParser", vnfFile); + Map<String, String> generateServiceMetadataToExpectedObject = generateServiceMetadataToExpectedObject(serviceReqDetails, service); + Metadata serviceMetadata = fdntCsarHelper.getServiceMetadata(); + Either<Boolean, Map<String, Object>> serviceToscaMetadataValidatorAgainstParser = ToscaValidation.serviceToscaMetadataValidatorAgainstParser(generateServiceMetadataToExpectedObject, serviceMetadata); + if (serviceToscaMetadataValidatorAgainstParser.isRight()) { + status.add(false); + } + } + return status; + } + + public List<Boolean> validateServiceNodeTemplateMetadataUsingParser(ISdcCsarHelper fdntCsarHelper, ResourceReqDetails resourceReqDetails, Resource resource, ComponentInstance componentInstanceDefinition, String vnfFile, List<Boolean> status) throws Exception { + if (fdntCsarHelper == null) { + reportSkipTestPrint("validateServiceNodeTemplateMetadataUsingParser", status); + } else { + reportStartTestPrint("validateServiceNodeTemplateMetadataUsingParser", vnfFile); + Map<String, String> generateServiceNodeTemplateMetadataToExpectedObject = generateServiceNodeTemplateMetadataToExpectedObject(resourceReqDetails, resource, componentInstanceDefinition); + List<NodeTemplate> serviceNodeTemplates = fdntCsarHelper.getServiceNodeTemplates(); + Metadata serviceNodeTemplateMetadata = serviceNodeTemplates.get(0).getMetaData(); + Either<Boolean, Map<String, Object>> serviceNodeTemplateToscaMetadataValidatorAgainstParser = ToscaValidation.serviceToscaMetadataValidatorAgainstParser(generateServiceNodeTemplateMetadataToExpectedObject, serviceNodeTemplateMetadata); + if (serviceNodeTemplateToscaMetadataValidatorAgainstParser.isRight()) { + status.add(false); + } + } + return status; + } + + //--------------------------Input verification-------------------------------- + + //--------------------------Resource-------------------------------- + public List<Boolean> validateResourceInputs(ToscaDefinition toscaMainAmdocsDefinition, ToscaDefinition toscaMainVfDefinition, String vnfFile, List<Boolean> status) throws Exception { + reportStartTestPrint("validateResourceInputs", vnfFile); + Map<String, ToscaInputsTopologyTemplateDefinition> expectedInputsMap = toscaMainAmdocsDefinition.getTopology_template().getInputs(); + Map<String, ToscaInputsTopologyTemplateDefinition> actualInputsMap = toscaMainVfDefinition.getTopology_template().getInputs(); + Either<Boolean, Map<String, Object>> toscaInputsValidator = ToscaValidation.toscaInputsValidator(expectedInputsMap, actualInputsMap); + if (toscaInputsValidator.isRight()) { + status.add(false); + } + return status; + } + + //--------------------------Service-------------------------------- + + public List<Boolean> validateServiceInputs(ToscaDefinition toscaExpectedMainServiceDefinition, ToscaDefinition toscaMainServiceDefinition, String vnfFile, List<Boolean> status) throws Exception { + reportStartTestPrint("validateServiceInputs", vnfFile); + Map<String, ToscaInputsTopologyTemplateDefinition> expectedInputsMap = toscaExpectedMainServiceDefinition.getTopology_template().getInputs(); + Map<String, ToscaInputsTopologyTemplateDefinition> actualInputsMap = toscaMainServiceDefinition.getTopology_template().getInputs(); + Either<Boolean, Map<String, Object>> toscaInputsValidator = ToscaValidation.toscaInputsValidator(expectedInputsMap, actualInputsMap); + if (toscaInputsValidator.isRight()) { + status.add(false); + } + return status; + } + + public List<Boolean> validateServiceModuleMetadata(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, ToscaDefinition toscaMainServiceDefinition, String vnfFile, List<Boolean> status) { + reportStartTestPrint("validateServiceModuleMetadata", vnfFile); + + Either<Boolean, Map<String, Object>> toscaServiceModuleMetadataValidator = ToscaValidation.serviceToscaGroupMetadataValidator(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition); + if (toscaServiceModuleMetadataValidator.isRight()) { + status.add(false); + } + return status; + } + + public List<Boolean> validateServiceModuleProperty(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, ToscaDefinition toscaMainServiceDefinition, String vnfFile, List<Boolean> status) { + reportStartTestPrint("validateServiceModuleProperty", vnfFile); + + Either<Boolean, Map<String, Object>> toscaServiceModulePropertyValidator = ToscaValidation.serviceToscaGroupPropertyValidator(expectedToscaServiceGroupsDefinitionObject, toscaMainServiceDefinition); + if (toscaServiceModulePropertyValidator.isRight()) { + status.add(false); + } + return status; + } + + //--------------------------Service verification against Pavel Parser-------------------------------- + public List<Boolean> validateServiceInputsUsingParser(ISdcCsarHelper fdntCsarHelper, ToscaDefinition toscaExpectedMainServiceDefinition, String vnfFile, List<Boolean> status) throws Exception { + if (fdntCsarHelper == null) { + reportSkipTestPrint("validateServiceInputsUsingParser", status); + } else { + reportStartTestPrint("validateServiceInputsUsingParser", vnfFile); + Map<String, ToscaInputsTopologyTemplateDefinition> expectedInputsMap = toscaExpectedMainServiceDefinition.getTopology_template().getInputs(); + Either<Boolean, Map<String, Object>> toscaInputsValidator = ToscaValidation.toscaInputsValidatorAgainstParser(expectedInputsMap, fdntCsarHelper); + if (toscaInputsValidator.isRight()) { + status.add(false); + } + } + return status; + } + + public List<Boolean> validateServiceModuleMetadataUsingParser(ISdcCsarHelper fdntCsarHelper, Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, String vnfFile, List<Boolean> status) { + reportStartTestPrint("validateServiceModuleMetadataUsingParser", vnfFile); + String customizationUUID = fdntCsarHelper.getServiceNodeTemplates().get(0).getMetaData().getValue("customizationUUID"); + List<Group> actualGroups = fdntCsarHelper.getVfModulesByVf(customizationUUID); + Either<Boolean, Map<String, Object>> toscaServiceModuleMetadataValidator = ToscaValidation.serviceToscaGroupMetadataValidatorUsingParser(expectedToscaServiceGroupsDefinitionObject, actualGroups); + if (toscaServiceModuleMetadataValidator.isRight()) { + status.add(false); + } + return status; + } + + public List<Boolean> validateServiceModulePropertyUsingParser(ISdcCsarHelper fdntCsarHelper, Map<String, ToscaGroupsTopologyTemplateDefinition> expectedToscaServiceGroupsDefinitionObject, String vnfFile, List<Boolean> status) { + reportStartTestPrint("validateServiceModuleMetadataUsingParser", vnfFile); + String customizationUUID = fdntCsarHelper.getServiceNodeTemplates().get(0).getMetaData().getValue("customizationUUID"); + List<Group> actualGroups = fdntCsarHelper.getVfModulesByVf(customizationUUID); + Either<Boolean, Map<String, Object>> toscaServiceModuleMetadataValidator = ToscaValidation.serviceToscaGroupPropertyValidatorUsingParser(expectedToscaServiceGroupsDefinitionObject, actualGroups); + if (toscaServiceModuleMetadataValidator.isRight()) { + status.add(false); + } + return status; + } + + private Map<String, ToscaGroupsTopologyTemplateDefinition> createExpectedToscaServiceGroupsDefinitionObject(Resource resource, Service service, List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition) { + Map<String, ToscaGroupsTopologyTemplateDefinition> toscaGroupsTopologyTemplateDefinitionMap = new HashMap<>(); + + for (TypeHeatMetaDefinition moduleType : listTypeHeatMetaDefinition) { + if (!moduleType.getTypeName().equals("artifacts")) { + for (GroupHeatMetaDefinition module : moduleType.getGroupHeatMetaDefinition()) { + ToscaGroupsTopologyTemplateDefinition toscaGroupsTopologyTemplateDefinition = new ToscaGroupsTopologyTemplateDefinition(); + String resourceModuleName = buildResourceModuleName(resource, module.getGroupName()); + ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition = setGroupMetadataFromResourceObject(resourceModuleName, resource); + if (!toscaServiceGroupsMetadataDefinition.equals("")) { + String serviceModuleName = buildServiceModuleName(service.getComponentInstances().get(0).getNormalizedName(), toscaServiceGroupsMetadataDefinition.getVfModuleModelName()); + toscaServiceGroupsMetadataDefinition = setGroupMetadataFromServiceObject(toscaServiceGroupsMetadataDefinition, serviceModuleName, service); + toscaGroupsTopologyTemplateDefinition.setMetadata(toscaServiceGroupsMetadataDefinition); + ToscaGroupPropertyDefinition toscaGroupPropertyDefinition = setGroupProperty(module); + toscaGroupsTopologyTemplateDefinition.setProperties(toscaGroupPropertyDefinition); + toscaGroupsTopologyTemplateDefinitionMap.put(serviceModuleName, toscaGroupsTopologyTemplateDefinition); + } else { + getExtendTest().log(Status.FAIL, "module name [" + module.getGroupName() + "] didn't represent in resource"); + } + } + } + } + return toscaGroupsTopologyTemplateDefinitionMap; + + } + + + private Map<String, VfModuleDefinition> createExpectedVfModuleDefinitionObject(Resource resource, Service service, List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition) { + Map<String, VfModuleDefinition> toscaGroupsTopologyTemplateDefinitionMap = new HashMap<>(); + + for (TypeHeatMetaDefinition moduleType : listTypeHeatMetaDefinition) { + if (!moduleType.getTypeName().equals("artifacts")) { + for (GroupHeatMetaDefinition module : moduleType.getGroupHeatMetaDefinition()) { + VfModuleDefinition toscaGroupsTopologyTemplateDefinition = new VfModuleDefinition(); + String resourceModuleName = buildResourceModuleName(resource, module.getGroupName()); + ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition = setGroupMetadataFromResourceObject(resourceModuleName, resource); + if (!toscaServiceGroupsMetadataDefinition.equals("")) { + toscaServiceGroupsMetadataDefinition = setGroupMetadataFromServiceObject(toscaServiceGroupsMetadataDefinition, resourceModuleName, service); + toscaGroupsTopologyTemplateDefinition.setMetadata(toscaServiceGroupsMetadataDefinition); + ToscaGroupPropertyDefinition toscaGroupPropertyDefinition = setGroupProperty(module); + toscaGroupsTopologyTemplateDefinition.setProperties(toscaGroupPropertyDefinition); + toscaGroupsTopologyTemplateDefinition.setArtifacts(getArtifactsUuidListForRI(module, resource, service)); + toscaGroupsTopologyTemplateDefinitionMap.put(toscaServiceGroupsMetadataDefinition.vfModuleModelName, toscaGroupsTopologyTemplateDefinition); + + } else { + getExtendTest().log(Status.FAIL, "module name [" + module.getGroupName() + "] didn't represent in resource"); + } + } + } + } + return toscaGroupsTopologyTemplateDefinitionMap; + + } + + private List<String> getArtifactsUuidListForRI(GroupHeatMetaDefinition module, Resource resource, Service service) { +//TODO check if each heat include its env file + List<String> artifactsUuidList = new ArrayList<>(); + ComponentInstance resourceInstance = null; + for (ComponentInstance componentInstance : service.getComponentInstances()) { + if (componentInstance.getUniqueId().contains(resource.getUniqueId())) { + resourceInstance = componentInstance; + break; + } + } + + Collection<ArtifactDefinition> artifactsDefinitionValues = resourceInstance.getDeploymentArtifacts().values(); + + for (HeatMetaFirstLevelDefinition moduleArtifactDefinition : module.getArtifactList()) { + for (ArtifactDefinition riArtifactDefinition : artifactsDefinitionValues) { + String heatYamlName = moduleArtifactDefinition.getFileName(); + String heatEnvName = heatYamlName.replaceAll("yaml|yml", "env"); + String riArtifactName = riArtifactDefinition.getArtifactName(); + if (riArtifactName.equals(heatYamlName) || riArtifactName.equals(heatEnvName)) { + artifactsUuidList.add(riArtifactDefinition.getArtifactUUID()); + } + } + } + + return artifactsUuidList; + } + + private ToscaGroupPropertyDefinition setGroupProperty(GroupHeatMetaDefinition module) { + ToscaGroupPropertyDefinition toscaGroupPropertyDefinition = new ToscaGroupPropertyDefinition(); + toscaGroupPropertyDefinition.setVf_module_label(module.getGroupName()); + Boolean isBase = module.getPropertyHeatMetaDefinition().getValue(); + if (isBase) { + toscaGroupPropertyDefinition.setInitial_count("1"); + toscaGroupPropertyDefinition.setMin_vf_module_instances("1"); + toscaGroupPropertyDefinition.setMax_vf_module_instances("1"); + toscaGroupPropertyDefinition.setVf_module_type("Base"); + } else { + toscaGroupPropertyDefinition.setInitial_count("0"); + toscaGroupPropertyDefinition.setMin_vf_module_instances("0"); + toscaGroupPropertyDefinition.setMax_vf_module_instances(""); + toscaGroupPropertyDefinition.setVf_module_type("Expansion"); + } + toscaGroupPropertyDefinition.setAvailability_zone_count(""); + toscaGroupPropertyDefinition.setVfc_list(""); + toscaGroupPropertyDefinition.setVf_module_description(""); + toscaGroupPropertyDefinition.setVolume_group(isVolumeGroup(module)); + + return toscaGroupPropertyDefinition; + } + + private String isVolumeGroup(GroupHeatMetaDefinition module) { + String isVolumeGroup = "false"; + for (HeatMetaFirstLevelDefinition artifactList : module.getArtifactList()) { + if (artifactList.getType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) { + isVolumeGroup = "true"; + return isVolumeGroup; + } + } + return isVolumeGroup; + } + + private Map<String, ToscaServiceGroupsMetadataDefinition> createExpectedToscaServiceGroupsPropertyDefinitionObject(Resource resource, Service service, List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition) { + + Map<String, ToscaServiceGroupsMetadataDefinition> toscaServiceGroupsMetadataDefinitionMap = new HashMap<>(); + for (TypeHeatMetaDefinition moduleType : listTypeHeatMetaDefinition) { + Map<String, String> groupProperty = new HashMap<>(); + + ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition = new ToscaServiceGroupsMetadataDefinition(); + for (GroupHeatMetaDefinition module : moduleType.getGroupHeatMetaDefinition()) { + String resourceModuleName = buildResourceModuleName(resource, module.getGroupName()); + toscaServiceGroupsMetadataDefinition = setGroupMetadataFromResourceObject(resourceModuleName, resource); + if (!toscaServiceGroupsMetadataDefinition.equals("")) { + String serviceModuleName = buildServiceModuleName(service.getComponentInstances().get(0).getNormalizedName(), toscaServiceGroupsMetadataDefinition.getVfModuleModelName()); + toscaServiceGroupsMetadataDefinition = setGroupMetadataFromServiceObject(toscaServiceGroupsMetadataDefinition, serviceModuleName, service); + toscaServiceGroupsMetadataDefinitionMap.put(serviceModuleName, toscaServiceGroupsMetadataDefinition); + } else { + getExtendTest().log(Status.FAIL, "module name [" + module.getGroupName() + "] didn't represent in resource"); + } + } + } + return toscaServiceGroupsMetadataDefinitionMap; + + } + + private ToscaServiceGroupsMetadataDefinition setGroupMetadataFromServiceObject(ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition, String serviceModuleName, Service service) { + for (GroupInstance groupInstance : service.getComponentInstances().get(0).getGroupInstances()) { + if (groupInstance.getName().contains(serviceModuleName)) { + toscaServiceGroupsMetadataDefinition.setVfModuleModelCustomizationUUID(groupInstance.getCustomizationUUID()); + return toscaServiceGroupsMetadataDefinition; + } + } + return toscaServiceGroupsMetadataDefinition; + } + + private ToscaServiceGroupsMetadataDefinition setGroupMetadataFromResourceObject(String resourceModuleName, Resource resource) { + ToscaServiceGroupsMetadataDefinition toscaServiceGroupsMetadataDefinition = new ToscaServiceGroupsMetadataDefinition(); + for (GroupDefinition group : resource.getGroups()) { + if (group.getName().contains(resourceModuleName)) { + toscaServiceGroupsMetadataDefinition.setVfModuleModelName(group.getName()); + toscaServiceGroupsMetadataDefinition.setVfModuleModelInvariantUUID(group.getInvariantUUID()); + toscaServiceGroupsMetadataDefinition.setVfModuleModelUUID(group.getGroupUUID()); + toscaServiceGroupsMetadataDefinition.setVfModuleModelVersion(group.getVersion()); + return toscaServiceGroupsMetadataDefinition; + } + } + return toscaServiceGroupsMetadataDefinition; + } + + public static String buildResourceModuleName(Resource resource, String groupName) { + return resource.getSystemName() + ".." + groupName + ".." + "module-"; + } + + public static String buildServiceModuleName(String resourceInstanceNormalizedName, String resourceGroupName) { + return resourceInstanceNormalizedName + ".." + resourceGroupName; + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + + + public static ToscaDefinition addGenericInputsToToscaObject(ToscaDefinition toscaDefinition, String genericName) throws Exception { + Resource genericResource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, genericName, "1.0"); + ToscaTopologyTemplateDefinition topologyTemplate = toscaDefinition.getTopology_template(); + Map<String, ToscaInputsTopologyTemplateDefinition> newInput = new HashMap<>(); + for (PropertyDefinition property : genericResource.getProperties()) { + ToscaInputsTopologyTemplateDefinition input = new ToscaInputsTopologyTemplateDefinition(); +// input.setConstraints(property.getConstraints()); + input.setDefault(property.getDefaultValue()); + input.setDescription(property.getDescription()); +// input.setEntry_schema(property.getSchema()); + input.setName(property.getName()); +// input.setRequired(property.get); + input.setStatus(property.getStatus()); + input.setType(property.getType()); + input.setValue(property.getValue()); + newInput.put(property.getName(), input); + } + + topologyTemplate.addInputs(newInput); + toscaDefinition.setTopology_template(topologyTemplate); + return toscaDefinition; + } + + public static ToscaDefinition setNameToToscaInput(ToscaDefinition toscaDefinition) { + Map<String, ToscaInputsTopologyTemplateDefinition> inputs = toscaDefinition.getTopology_template().getInputs(); + for (String name : inputs.keySet()) { + inputs.get(name).setName(name); + } + toscaDefinition.getTopology_template().setInputs(inputs); + return toscaDefinition; + } + + public static ToscaDefinition addAndGenerateResourceMetadataToExpectedObject(ToscaDefinition toscaDefinition, ResourceReqDetails resourceReqDetails, Component component) { + + Map<String, String> metadata = convertResourceMetadataToMap(resourceReqDetails, component); + toscaDefinition.setMetadata(metadata); + return toscaDefinition; + } + + public static Map<String, String> convertResourceMetadataToMap(ResourceReqDetails resourceReqDetails, Component component) { + Map<String, String> metadata = new HashMap<>(); + + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.CATEGORY.value, resourceReqDetails.getCategories().get(0).getName()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.DESCRIPTION.value, resourceReqDetails.getDescription()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.INVARIANT_UUID.value, component.getInvariantUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.TYPE.value, resourceReqDetails.getResourceType()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.UUID.value, component.getUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.NAME.value, component.getName()); + + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.RESOURCE_VENDOR_NAME.value, resourceReqDetails.getVendorName()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.RESOURCE_VENDOR_MODEL_NUMBER.value, resourceReqDetails.getResourceVendorModelNumber()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.RESOURCE_VENDOR_RELEASE.value, resourceReqDetails.getVendorRelease()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SUBCATEGORY.value, resourceReqDetails.getCategories().get(0).getSubcategories().get(0).getName()); + return metadata; + } + + public static Map<String, String> convertResourceNodeTemplateMetadataToMap(ComponentInstance componentInstance) throws Exception { + + Resource resource = AtomicOperationUtils.getResourceObject(componentInstance.getComponentUid()); + Map<String, String> metadata = new HashMap<>(); + + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.CATEGORY.value, resource.getCategories().get(0).getName()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.DESCRIPTION.value, resource.getDescription()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.INVARIANT_UUID.value, resource.getInvariantUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.TYPE.value, resource.getResourceType().toString()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.UUID.value, resource.getUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.NAME.value, resource.getName()); + + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.RESOURCE_VENDOR_NAME.value, resource.getVendorName()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.RESOURCE_VENDOR_MODEL_NUMBER.value, resource.getResourceVendorModelNumber()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.RESOURCE_VENDOR_RELEASE.value, resource.getVendorRelease()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SUBCATEGORY.value, resource.getCategories().get(0).getSubcategories().get(0).getName()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.CUSTOMIZATION_UUID.value, componentInstance.getCustomizationUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.VERSION.value, componentInstance.getComponentVersion()); + + return metadata; + } + + public static Map<String, String> generateServiceNodeTemplateMetadataToExpectedObject(ResourceReqDetails resourceReqDetails, Component component, ComponentInstance componentInstanceDefinition) { + + Map<String, String> metadata = convertResourceMetadataToMap(resourceReqDetails, component); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.CUSTOMIZATION_UUID.value, componentInstanceDefinition.getCustomizationUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.VERSION.value, componentInstanceDefinition.getComponentVersion()); + + return metadata; + } + + public static Map<String, Map<String, String>> generateResourceNodeTemplateMetadataToExpectedObject(Component component) throws Exception { + + Map<String, Map<String, String>> resourcesNodeTemplateMetadataMap = new HashMap<>(); + if (component.getComponentInstances() != null && !component.getComponentInstances().isEmpty()) { + for (ComponentInstance componentInstance : component.getComponentInstances()) { + Map<String, String> metadata = convertResourceNodeTemplateMetadataToMap(componentInstance); + resourcesNodeTemplateMetadataMap.put(componentInstance.getName(), metadata); + } + } + return resourcesNodeTemplateMetadataMap; + } + + public static Map<String, String> generateServiceMetadataToExpectedObject(ServiceReqDetails serviceReqDetails, Component component) { + + Map<String, String> metadata = new HashMap<>(); + + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.CATEGORY.value, serviceReqDetails.getCategories().get(0).getName()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.DESCRIPTION.value, serviceReqDetails.getDescription()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.INVARIANT_UUID.value, component.getInvariantUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.TYPE.value, "Service"); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.UUID.value, component.getUUID()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.NAME.value, component.getName()); + + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SERVICE_TYPE.value, serviceReqDetails.getServiceType()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SERVICE_ROLE.value, serviceReqDetails.getServiceRole()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.NAMING_POLICY.value, serviceReqDetails.getNamingPolicy()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.ECOMP_GENERATED_NAMING.value, serviceReqDetails.getEcompGeneratedNaming().toString()); + metadata.put(ToscaMetadataFieldsPresentationEnum.ToscaMetadataFieldsEnum.SERVICE_ECOMP_NAMING.value, serviceReqDetails.getEcompGeneratedNaming().toString());//equals to ECOMP_GENERATED_NAMING + + return metadata; + } + + public static void reportStartTestPrint(String testName, String vnfFile) { +// reportMessageInColor("info", "blue", "Running test \" + testName + \" with zip file - \" + vnfFile"); + SetupCDTest.getExtendTest().log(Status.INFO, "<html><font color=\"blue\"> Running test " + testName + " with zip file - " + vnfFile + "</font></html>"); + } + + public static void reportSkipTestPrint(String testName, List<Boolean> status) { +// reportMessageInColor("error", "orange", "Skip test \" + testName + \" due to previous tosca parser error"); + SetupCDTest.getExtendTest().log(Status.ERROR, "<html><font color=\"orange\"> Skip test " + testName + " due to previous tosca parser error" + "</font></html>"); + status.add(false); + } + + public static void reportMessageInColor(String status, String color, String message) { + String printLine = getReportMessageInColor(color, message); + SetupCDTest.getExtendTest().log(Status.valueOf(status), printLine); +// SetupCDTest.getExtendTest().log(Status.valueOf(status), getReportMessageInColor(color, message)); + } + + /** + * @param color = red, green, orange, blue ... + * @param message - message string + * @return string in desired color + */ + public static String getReportMessageInColor(String color, String message) { + String returnValue = ("<html><font color=\\\"+color+\"\">" + message + "</font></html>").toString(); + return returnValue; + } + +/* @Test() + public void printTest(){ + System.out.println("print"); + reportMessageInColor("ERROR", "green", "green"); + reportMessageInColor("INFO", "orange", "orange"); + reportMessageInColor("INFO", "red", "red"); + }*/ + +/* @Test + public void allottedResourceModelTest() throws Exception{ + List<Boolean> status = new ArrayList<>(); + + List<String> fileNamesFromFolder = OnboardingUtils.getVnfNamesFileListExcludeToscaParserFailure(); + List<String> newRandomFileNamesFromFolder = OnbordingDataProviders.getRandomElements(1, fileNamesFromFolder); + String vnfFile = newRandomFileNamesFromFolder.get(0); + setLog(vnfFile); + String filePath = FileHandling.getVnfRepositoryPath(); + File filesFolder = new File(SetupCDTest.getWindowTest().getDownloadDirectory()); + + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(ResourceCategoryEnum.ALLOTTED_RESOURCE_SERVICE_ADMIN); + resourceReqDetails = createCustomizedVsp(resourceReqDetails, filePath, vnfFile); + + ToscaDefinition toscaMainAmdocsDefinition = downloadAndGetToscaMainYamlObjectUI(resourceReqDetails, filesFolder); + toscaMainAmdocsDefinition = addGenericPropertiesToToscaDefinitionObject(toscaMainAmdocsDefinition, GENERIC_VF); + + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + ToscaDefinition toscaMainVfDefinition = downloadAndGetToscaMainYamlObjectApi(resource, filesFolder); + + status = validateVfMetadata(toscaMainAmdocsDefinition, toscaMainVfDefinition, resourceReqDetails, resource, vnfFile, status); + status = validateResourceNodeTemplateMetadata(toscaMainVfDefinition, resource, vnfFile, status); + status = validateResourceInputs(toscaMainAmdocsDefinition, toscaMainVfDefinition, vnfFile, status); + + if(status.contains(false)){ + SetupCDTest.getExtendTest().log(Status.FAIL, "Summary: allottedResourceModelTest tosca validation test failed with zip file " + vnfFile); + Assert.assertFalse(true); + } + }*/ + + + // help method to toscaValidation tests + private ISdcCsarHelper initSdcCsarHelper(File serviceCsarFileName, File filesFolder) { + + ISdcCsarHelper fdntCsarHelper; + try { + SetupCDTest.getExtendTest().log(Status.INFO, "Tosca parser is going to convert service csar file to ISdcCsarHelper object..."); + fdntCsarHelper = factory.getSdcCsarHelper(filesFolder.getPath() + serviceCsarFileName); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.ERROR, "Tosca parser FAILED to convert service csar file to ISdcCsarHelper object..."); + SetupCDTest.getExtendTest().log(Status.FAIL, e); + fdntCsarHelper = null; + } + return fdntCsarHelper; + } + + + /** + * @param resourceReqDetails to create Vsp + * @return updated resourceReqDetails after Vsp was created + */ + private ResourceReqDetails createCustomizedVsp(ResourceReqDetails resourceReqDetails, String filePath, String vnfFile) throws Exception { + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUtillViaApis.createVspViaApis(resourceReqDetails, filePath, vnfFile, user); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + return resourceReqDetails; + } + + /** + * @param resourceReqDetails to download csar file via UI + * @return Tosca definition object from main yaml file + */ + private ToscaDefinition downloadAndGetToscaMainYamlObjectUI(ResourceReqDetails resourceReqDetails, File filesFolder) throws Exception { + DownloadManager.downloadCsarByNameFromVSPRepository(resourceReqDetails.getName(), false); + File amdocsCsarFileName = FileHandling.getLastModifiedFileNameFromDir(filesFolder.getAbsolutePath()); + return ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(amdocsCsarFileName); + } + + /** + * @param toscaMainAmdocsDefinition object to add generic properties + * @param genericName resource name + * @return updated toscaMainAmdocsDefinition object + */ + private ToscaDefinition addGenericPropertiesToToscaDefinitionObject(ToscaDefinition toscaMainAmdocsDefinition, String genericName) throws Exception { + toscaMainAmdocsDefinition = setNameToToscaInput(toscaMainAmdocsDefinition); + toscaMainAmdocsDefinition = addGenericInputsToToscaObject(toscaMainAmdocsDefinition, genericName); + return toscaMainAmdocsDefinition; + } + + /** + * @param resource to download csar file via API + * @return Tosca definition object from main yaml file + */ + private ToscaDefinition downloadAndGetToscaMainYamlObjectApi(Resource resource, File filesFolder) throws Exception { + File vfCsarFileName = new File(File.separator + "VfCsar_" + ElementFactory.generateUUIDforSufix() + ".csar"); + OnboardingUtillViaApis.downloadToscaCsarToDirectory(resource, new File(filesFolder.getPath() + vfCsarFileName)); + return ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(filesFolder.getPath() + vfCsarFileName)); + } + + +} + + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/UpgradeServices.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/UpgradeServices.java new file mode 100644 index 0000000000..a0a176ac2a --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/UpgradeServices.java @@ -0,0 +1,459 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.PortMirroringUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.verificator.PropertiesAssignmentVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.ConnectionWizardPopUpObject; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.PortMirrioringConfigurationObject; +import org.onap.sdc.frontend.ci.tests.datatypes.PortMirroringEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesAssignmentPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertyNameBuilder; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.TesterOperationPage; +import org.onap.sdc.frontend.ci.tests.pages.UpgradeServicesPopup; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.FileHandling; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.testng.Assert; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.Map; + +public class UpgradeServices extends SetupCDTest { + + + private static final int CREATIN_UPDATE_BUTTON_TIMEOUT = 10 * 60; + private User sdncDesignerDetails = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + private String filePath; + + @BeforeClass + public void beforeClass() { + filePath = org.onap.sdc.frontend.ci.tests.utilities.FileHandling.getFilePath(""); + } + + @Test + public void upgradeVfOnServiceLevel() throws Throwable { + String vnfFile = "2016-227_vmme_vmme_30_1610_e2e.zip"; + //1. Import VSP, create VF, certify + Resource vfResource = createAndCertifyVFfromVSP(vnfFile); + //2. Create CR, certify + ResourceReqDetails crMetaData = createCRAndCertify(); + //3. Create PNF, certify + ResourceReqDetails pnfMetaData = createPnfAndCertify(); + + //4. Create Service1. Service composition - add 2 VFi + Service service1 = createService(); + getExtendTest().log(Status.INFO, "Add VFi to service twice"); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CanvasManager canvasManager1 = createCanvasManager(service1); + CanvasElement vfElementVmme1 = canvasManager1.createElementOnCanvas(vfResource.getName()); + CanvasElement vfElementVmme11 = canvasManager1.createElementOnCanvas(vfResource.getName()); + + //5. Add CRi, PNFi and PMC to Service1 + getExtendTest().log(Status.INFO, "Add PMC element to service"); + CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); + CanvasElement pmcElement = canvasManager1.createElementOnCanvas(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); + getExtendTest().log(Status.INFO, "Add CR and PNF elements to service"); + canvasManager1.createElementOnCanvas(crMetaData.getName()); + canvasManager1.createElementOnCanvas(pnfMetaData.getName()); + + //6. Link between VF and PMC. Give values to capability properties. Certify Service1. + ConnectionWizardPopUpObject connectionWizardPopUpObject = new ConnectionWizardPopUpObject("", "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_SOURCE_CAP.getValue()); + Map<String, String> capPropValues1 = canvasManager1.linkElementsWithCapPropAssignment(vfElementVmme1, + pmcElement, connectionWizardPopUpObject); //link elements, assign values to properties and save map of values for later validation + certifyServiceInUI(service1); + service1.setVersion("1.0"); + service1 = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service1.getName(), service1.getVersion()); + String vf1CustUuidOrig = AtomicOperationUtils.getServiceComponentInstanceByName( + service1, vfElementVmme1.getElementNameOnCanvas(), true).getCustomizationUUID(); + + //7. Create Service2. Service composition - add VFi. Start certifying Service2 ("certification in progress" stage) + Service service2 = createService(); + getExtendTest().log(Status.INFO, "Add VFi to service"); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CanvasManager canvasManager2 = createCanvasManager(service2); + CanvasElement vfElementVmme2 = canvasManager2.createElementOnCanvas(vfResource.getName()); + getExtendTest().log(Status.INFO, "Start service certification"); + AtomicOperationUtils.changeComponentState(service2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.STARTCERTIFICATION, true).getLeft(); + service2 = AtomicOperationUtils.getServiceObject(service2.getUniqueId()); + String vf2CustUuidOrig = AtomicOperationUtils.getServiceComponentInstanceByName( + service2, vfElementVmme2.getElementNameOnCanvas(), true).getCustomizationUUID(); + + //8. Create Service3. Service composition - add VFi. Leave service in "checked out" state + Service service3 = createService(); + getExtendTest().log(Status.INFO, "Add VFi to service"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + CanvasManager canvasManager3 = createCanvasManager(service3); + CanvasElement vfElementVmme3 = canvasManager3.createElementOnCanvas(vfResource.getName()); + service3 = AtomicOperationUtils.getServiceObject(service3.getUniqueId()); //updated + String vf3CustUuidOrig = AtomicOperationUtils.getServiceComponentInstanceByName( + service3, vfElementVmme3.getElementNameOnCanvas(), true).getCustomizationUUID(); + + //9. VF - checkout, save, click "certify" + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(vfResource.getName()); + GeneralPageElements.clickCheckoutButton(); + GeneralPageElements.clickCreateUpdateButton(CREATIN_UPDATE_BUTTON_TIMEOUT); + GeneralPageElements.clickCertifyButtonNoUpgradePopupDismiss(vfResource.getName()); + + //10. Validate that Service1 can be upgraded (checked), Service2 and Service3 are locked + //TODO - add validation in UI + + //11. Click Upgrade button + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.UPGRADE_SERVICES_OK.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.UPGRADE_SERVICES_CLOSE.getValue()); + + //12. Open Service1, verify version (1.1), state(checked in), VFi version (v2.0) + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service1.getName()); + ServiceVerificator.verifyVersionUI("1.1"); + ServiceVerificator.verifyServiceLifecycleInUI(LifeCycleStateEnum.CHECKIN); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager4 = CanvasManager.getCanvasManager(); + canvasManager4.clickOnCanvaElement(vfElementVmme1); + ServiceVerificator.verifyResourceInstanceVersionUI("2.0"); + canvasManager4.clickOnCanvaElement(vfElementVmme11); + ServiceVerificator.verifyResourceInstanceVersionUI("2.0"); + + //13. Verify that VFi CustomizationID is different + service1.setVersion("1.1"); + service1 = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service1.getName(), service1.getVersion()); //updated + String vf1CustUuidUpd = AtomicOperationUtils.getServiceComponentInstanceByName( + service1, vfElementVmme1.getElementNameOnCanvas(), true).getCustomizationUUID(); + Assert.assertTrue(!vf1CustUuidOrig.equals(vf1CustUuidUpd)); + + //14. Verify that capabilities properties assignment is kept + canvasManager4.openLinkPopupReqsCapsConnection(vfElementVmme1, pmcElement); //open connection wizard + Map<String, String> capPropValues2 = canvasManager4.connectionWizardCollectCapPropValues(); //collect cap prop values + Assert.assertTrue(capPropValues1.equals(capPropValues2)); // compare cap prop values before and after changing VF version + canvasManager4.clickSaveOnLinkPopup(); + + //15. Open Service2, verify version (0.1), state ("in testing"), VFi version (1.0) and VFi Customization UUID (hasn't changed) + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service2.getName()); + ServiceVerificator.verifyVersionUI("0.1"); + ServiceVerificator.verifyServiceLifecycleInUI(LifeCycleStateEnum.IN_TESTING); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager5 = CanvasManager.getCanvasManager(); + canvasManager5.clickOnCanvaElement(vfElementVmme2); + ServiceVerificator.verifyResourceInstanceVersionUI("1.0"); + service2 = AtomicOperationUtils.getServiceObject(service2.getUniqueId()); //updated + String vf2CustUuidUpd = AtomicOperationUtils.getServiceComponentInstanceByName( + service2, vfElementVmme2.getElementNameOnCanvas(), true).getCustomizationUUID(); + Assert.assertTrue(vf2CustUuidOrig.equals(vf2CustUuidUpd)); + + //16. Open Service3, verify version (0.1), state ("checked out"), VFi version (1.0) and VFi Customization UUID (hasn't changed) + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service3.getName()); + ServiceVerificator.verifyVersionUI("0.1"); + ServiceVerificator.verifyServiceLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager6 = CanvasManager.getCanvasManager(); + canvasManager6.clickOnCanvaElement(vfElementVmme3); + ServiceVerificator.verifyResourceInstanceVersionUI("1.0"); + service3 = AtomicOperationUtils.getServiceObject(service3.getUniqueId()); //updated + String vf3CustUuidUpd = AtomicOperationUtils.getServiceComponentInstanceByName( + service3, vfElementVmme3.getElementNameOnCanvas(), true).getCustomizationUUID(); + Assert.assertTrue(vf3CustUuidOrig.equals(vf3CustUuidUpd)); + + //17. Open CR, checkout, certify. Verify there is no upgrade popup + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(crMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCertifyButton(crMetaData.getName()); + Assert.assertTrue(!UpgradeServicesPopup.isUpgradePopupShown()); + + //18. Open PNF, checkout, certify. Verify there is no upgrade popup + GeneralUIUtils.findComponentAndClick(pnfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + ResourceGeneralPage.clickCertifyButton(pnfMetaData.getName()); + Assert.assertTrue(!UpgradeServicesPopup.isUpgradePopupShown()); + } + + @Test + public void upgradeAllottedVfOnServiceLevel() throws Throwable { + String propUUID = "depending_service_uuid"; + String propInvUUID = "depending_service_invariant_uuid"; + String propName = "depending_service_name"; + + //1. Create Service1, certify + Service service1 = createService(); + getExtendTest().log(Status.INFO, "Certify Service1"); + AtomicOperationUtils.changeComponentState(service1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + String serviceName = service1.getName(); + String serviceInvUUID = service1.getInvariantUUID(); + String serviceUUIDv1 = service1.getUUID(); + + //2. Import AllottedResource yaml, create VFC, certify + String fileName = "Allottedresource.yml"; + ResourceReqDetails vfcMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, + ResourceCategoryEnum.ALLOTTED_RESOURCE, getUser()); + ResourceUIUtils.importVfc(vfcMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCertifyButton(vfcMetaData.getName()); + + //3. Create VF, add VFCi to canvas + ResourceReqDetails vfMetaData = createVFviaAPI(ResourceCategoryEnum.ALLOTTED_RESOURCE_TUNNEL_XCONNECT); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager1 = CanvasManager.getCanvasManager(); + CanvasElement vfcElement1 = canvasManager1.createElementOnCanvas(vfcMetaData.getName()); + + //4. VF Properties Assignment: edit values of depending service properties, certify VF + CompositionPage.moveToPropertiesScreen(); + PropertiesAssignmentPage.findSearchBoxAndClick(propName); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propName), serviceName); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propUUID); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propUUID), serviceUUIDv1); + PropertiesAssignmentPage.clickOnSaveButton(); + PropertiesAssignmentPage.findSearchBoxAndClick(propInvUUID); + PropertiesAssignmentPage.editPropertyValue(PropertyNameBuilder.buildSimpleField(propInvUUID), serviceInvUUID); + PropertiesAssignmentPage.clickOnSaveButton(); + ResourceGeneralPage.clickCertifyButton(vfMetaData.getName()); + + //5. Create Service2, add VFi to Service2, certify Service2 + Service service2 = createService(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CanvasManager canvasManager2 = createCanvasManager(service2); + CanvasElement vfElement1 = canvasManager2.createElementOnCanvas(vfMetaData.getName()); + getExtendTest().log(Status.INFO, "Certify Service2"); + AtomicOperationUtils.changeComponentState(service2, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //6. Create Service3, add VFi to Service3, leave Service3 in checked-out state + Service service3 = createService(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + CanvasManager canvasManager3 = createCanvasManager(service3); + CanvasElement vfElement2 = canvasManager3.createElementOnCanvas(vfMetaData.getName()); + + //7. Check out and certify Service1 (keep new UUID) + AtomicOperationUtils.changeComponentState(service1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(service1, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + service1 = AtomicOperationUtils.getServiceObject(service1.getUniqueId()); + String serviceUUIDv2 = service1.getUUID(); + + //8. Open Service1 and click “Upgrade Services” button + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service1.getName()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.UPDATE_SERVICES_BUTTON.getValue()).click(); + + //9. Validate that Service2 can be upgraded (checked), Service3 is locked + //TODO - add validation in UI + + //10. Click Upgrade button + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.UPDATE_SERVICES_OK.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.UPGRADE_SERVICES_CLOSE.getValue()); + + //11. Open VF, verify that version is 2.0 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + VfVerificator.verifyVersionUI("2.0"); + + //12. VF properties assignment - verify that UUID value is updated, other values are the same + ResourceGeneralPage.getLeftMenu().moveToPropertiesAssignmentScreen(); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propUUID), serviceUUIDv2); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propInvUUID), serviceInvUUID); + PropertiesAssignmentVerificator.validatePropertyValue(PropertyNameBuilder.buildSimpleField(propName), serviceName); + + //13. Open Service2, verify version 1.1 and state "in design check in", select VFi, verify version 2.0 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service2.getName()); + ServiceVerificator.verifyVersionUI("1.1"); + ServiceVerificator.verifyServiceLifecycleInUI(LifeCycleStateEnum.CHECKIN); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager4 = CanvasManager.getCanvasManager(); + canvasManager4.clickOnCanvaElement(vfElement1); + ServiceVerificator.verifyResourceInstanceVersionUI("2.0"); + + //14. Open Service3, select VFi in composition, verify version 1.0 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service3.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager5 = CanvasManager.getCanvasManager(); + canvasManager5.clickOnCanvaElement(vfElement2); + ServiceVerificator.verifyResourceInstanceVersionUI("1.0"); + } + + @Test + public void upgradeServiceProxyOnServiceLevel() throws Throwable { + //1. Create Port Mirroring Service1, certify + PortMirrioringConfigurationObject portMirrioringConfigurationObject = PortMirroringUtils.createPortMirriongConfigurationStructure(true); + Service service1 = portMirrioringConfigurationObject.getService(); + Service serviceSource = portMirrioringConfigurationObject.getServiceContainerVmme_Source(); + CanvasElement pmcElement = portMirrioringConfigurationObject.getPortMirroringConfigurationElement(); + CanvasElement sourceElement = portMirrioringConfigurationObject.getServiceElementVmmeSourceName(); + Map<String, String> capPropValues1 = portMirrioringConfigurationObject.getCapPropValues(); + certifyServiceInUI(service1); + service1 = AtomicOperationUtils.getServiceObject(service1.getUniqueId()); + String serviceSourceName = portMirrioringConfigurationObject.getServiceElementVmmeSourceName().getElementNameOnCanvas(); + String sourceUuidOrig = AtomicOperationUtils.getServiceComponentInstanceByName( + service1, serviceSourceName, true).getCustomizationUUID(); + + //2. Create Service2, add source service to it + Service service2 = createService(); + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + CanvasManager canvasManager1 = createCanvasManager(service2); + CanvasElement serviceSourceElement = canvasManager1.createElementOnCanvas(serviceSource.getName()); + + //3. Checkout and certify serviceSource + AtomicOperationUtils.changeComponentState(serviceSource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKOUT, true).getLeft(); + AtomicOperationUtils.changeComponentState(serviceSource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + serviceSource = AtomicOperationUtils.getServiceObject(serviceSource.getUniqueId()); + + //4. Open Service2, click Update button + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(serviceSource.getName()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.UPDATE_SERVICES_BUTTON.getValue()).click(); + + //5. Validate that Service1 can be upgraded (checked), Service2 is locked + //TODO - add validation in UI + + //6. Click Upgrade button + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.UPDATE_SERVICES_OK.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.UPGRADE_SERVICES_CLOSE.getValue()); + + //7. Open Service1, verify version 1.1 and state "in design check in", select VFi, verify version 2.0 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service1.getName()); + ServiceVerificator.verifyVersionUI("1.1"); + ServiceVerificator.verifyServiceLifecycleInUI(LifeCycleStateEnum.CHECKIN); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager2 = CanvasManager.getCanvasManager(); + canvasManager2.clickOnCanvaElement(serviceSourceElement); + ServiceVerificator.verifyResourceInstanceVersionUI("2.0"); + + //8. Verify that capabilities properties values are kept + canvasManager2.openLinkPopupReqsCapsConnection(sourceElement, pmcElement); //open connection wizard + Map<String, String> capPropValues2 = canvasManager2.connectionWizardCollectCapPropValues(); //collect cap prop values + Assert.assertTrue(capPropValues1.equals(capPropValues2)); // compare cap prop values before and after changing VF version + canvasManager2.clickSaveOnLinkPopup(); + + //9. Verify that CustomizationUUID of service source instance is changed + service1.setVersion("1.1"); //updated + service1 = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service1.getName(), service1.getVersion()); + String sourceUuidUpd = AtomicOperationUtils.getServiceComponentInstanceByName( + service1, serviceSourceName, true).getCustomizationUUID(); + Assert.assertTrue(!sourceUuidOrig.equals(sourceUuidUpd)); + + //10. Open Service3, select VFi in composition, verify version 1.0 + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + GeneralUIUtils.findComponentAndClick(service2.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager3 = CanvasManager.getCanvasManager(); + canvasManager3.clickOnCanvaElement(serviceSourceElement); + ServiceVerificator.verifyResourceInstanceVersionUI("1.0"); + } + + + private CanvasManager createCanvasManager(Service service1) throws Exception { + GeneralUIUtils.findComponentAndClick(service1.getName()); + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + return CanvasManager.getCanvasManager(); + } + + private void certifyServiceInUI(Service service1) throws Exception { + getExtendTest().log(Status.INFO, "Certify Service"); + ServiceGeneralPage.clickSubmitForTestingButton(service1.getName()); + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(service1.getName()); + TesterOperationPage.certifyComponent(service1.getName()); + reloginWithNewRole(UserRoleEnum.DESIGNER); + } + + private Service createService() throws Exception { + ServiceReqDetails serviceReqDetails1 = OnboardingUtillViaApis.prepareServiceDetailsBeforeCreate(sdncDesignerDetails); + getExtendTest().log(Status.INFO, "Create Service " + serviceReqDetails1.getName()); + return AtomicOperationUtils.createCustomService(serviceReqDetails1, UserRoleEnum.DESIGNER, true).left().value(); + } + + private ResourceReqDetails createPnfAndCertify() throws Exception { + ResourceReqDetails pnfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.PNF, getUser()); + ResourceUIUtils.createPNF(pnfMetaData, getUser()); + ResourceGeneralPage.clickCertifyButton(pnfMetaData.getName()); + return pnfMetaData; + } + + private Resource createAndCertifyVFfromVSP(String vnfFile) throws Exception { + String filePath = FileHandling.getPortMirroringRepositoryPath(); + getExtendTest().log(Status.INFO, "Going to upload VNF " + vnfFile); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createAndFillVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails, + vendorLicenseModel, null); + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource vfResource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + vfResource = (Resource) AtomicOperationUtils.changeComponentState(vfResource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + return vfResource; + } + + private ResourceReqDetails createCRAndCertify() throws Exception { + ResourceReqDetails crMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.CR, getUser()); + ResourceUIUtils.createCR(crMetaData, getUser()); + ResourceGeneralPage.clickCertifyButton(crMetaData.getName()); + return crMetaData; + } + + private ResourceReqDetails createVFviaAPI(ResourceCategoryEnum resourceCategory) { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, resourceCategory, getUser()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating VF %s", vfMetaData.getName())); + AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value(); + return vfMetaData; + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VFCArtifacts.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VFCArtifacts.java new file mode 100644 index 0000000000..34d2c9c9be --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VFCArtifacts.java @@ -0,0 +1,381 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.apache.http.HttpStatus; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.execute.devCI.ArtifactFromCsar; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.onap.sdc.frontend.ci.tests.verificator.VFCArtifactVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.DownloadManager; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.testng.Assert.assertTrue; + +public class VFCArtifacts extends SetupCDTest { + + private static final String DEPLOYMENT = "Deployment"; + private static final String INFORMATIONAL = "Informational"; + private static final String ARTIFACTS = "artifacts"; + private static final String DEPLOYMENT_ARTIFACTS = "deploymentArtifacts"; + private String filePath; + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath("VFCArtifacts"); + } + + @Test + public void ImportMultiVFCTest_TC1407998() throws Exception { + + String csarFile = "Import_Multi_VFC.csar"; + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + RestResponse getResponse = RestCDUtils.getResource(resourceMetaData, getUser()); + assertTrue(getResponse.getErrorCode().intValue() == HttpStatus.SC_OK); + + Map<String, LinkedList<HeatMetaFirstLevelDefinition>> expectedArtifactMap = verifyVfcArtifacts(filePath, csarFile, resourceMetaData, getResponse); + + VFCArtifactVerificator.verifyVFCArtifactsNotInVFArtifactList(resourceMetaData, getUser(), getResponse, expectedArtifactMap); + + + } + + @Test + public void updateCsarWithVFCArtifacts_ModifyArtifacts_TC1449482() throws Exception { + + String csarFile = "LDSA-ORIG.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + Map<String, Object> artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + csarFile); + List<String> vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys) { + VFCArtifactVerificator.setActualVfcArtifactList(key, resourceMetaData, getUser()); + } + + String updatedCsarFile = "LDSA-MODIFY.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + Map<String, Object> updatedArtifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + updatedCsarFile); + List<String> updatedVfcKeys = updatedArtifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : updatedVfcKeys) { + verifyVfcInstanceArtifacts(resourceMetaData, null, updatedArtifactsFromCsar, key); + VFCArtifactVerificator.verifyVfcArtifactUpdated(key, resourceMetaData, getUser()); + } + } + + @Test + public void updateCsarWithVFCArtifacts_DeleteAndAddArtifacts_TC1449473() throws Exception { + + String csarFile = "LDSA-ORIG.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + String updatedCsarFile = "LDSA-DELETE-ADD.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + verifyVfcArtifacts(filePath, updatedCsarFile, resourceMetaData, null); + } + + @Test + public void updateCsarWithVFCArtifacts_AddFirstVFCIdentifier_TC1425896() throws Exception { + + String csarFile = "LDSA-ORIG-OLD_STRUCTURE.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + VFCArtifactVerificator.verifyNoVfcArtifacts(resourceMetaData, getUser(), null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + String[] artifactNamesFromFile = ArtifactFromCsar.getArtifactNamesFromCsar(filePath, csarFile); + String[] artifactsFromFileBeforeUpdate = DeploymentArtifactPage.verifyArtifactsExistInTable(artifactNamesFromFile); + DeploymentArtifactPage.getLeftMenu().moveToGeneralScreen(); + + String updatedCsarFile = "LDSA-ADD.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + verifyVfcArtifacts(filePath, updatedCsarFile, resourceMetaData, null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(artifactsFromFileBeforeUpdate); + } + + + @Test + public void updateCsarWithVFCArtifacts_AddAdditionalVFCIdentifier_TC1425898() throws Exception { + + String csarFile = "LDSA-SINGLE.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + Map<String, Object> artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + csarFile); + List<String> vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys) { + VFCArtifactVerificator.setActualVfcArtifactList(key, resourceMetaData, getUser()); + } + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + String[] artifactNamesFromFile = ArtifactFromCsar.getArtifactNamesFromCsar(filePath, csarFile); + String[] artifactsFromFileBeforeUpdate = DeploymentArtifactPage.verifyArtifactsExistInTable(artifactNamesFromFile); + DeploymentArtifactPage.getLeftMenu().moveToGeneralScreen(); + + String updatedCsarFile = "LDSA-MULTI.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + Map<String, Object> updatedArtifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filePath + updatedCsarFile); + List<String> updatedVfcKeys = updatedArtifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : updatedVfcKeys) { + verifyVfcInstanceArtifacts(resourceMetaData, null, updatedArtifactsFromCsar, key); + if (vfcKeys.contains(key)) { + VFCArtifactVerificator.verifyVFCArtifactNotChanged(key, resourceMetaData, getUser()); + } + } + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(artifactsFromFileBeforeUpdate); + } + + @Test + public void updateCsarWithVFCArtifacts_DeleteAll_TC1425581() throws Exception { + + String csarFile = "LDSA-ORIG.csar"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType("ciRes", NormativeTypesEnum.ROOT, ResourceCategoryEnum.APPLICATION_L4_DATABASE, getUser().getUserId(), ResourceTypeEnum.VF.toString()); + resourceMetaData.setVersion("0.1"); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, csarFile, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + String[] artifactNamesFromFile = ArtifactFromCsar.getArtifactNamesFromCsar(filePath, csarFile); + String[] artifactsFromFileBeforeUpdate = DeploymentArtifactPage.verifyArtifactsExistInTable(artifactNamesFromFile); + DeploymentArtifactPage.getLeftMenu().moveToGeneralScreen(); + + String updatedCsarFile = "LDSA-DELETE-ALL.csar"; + ResourceUIUtils.updateVfWithCsar(filePath, updatedCsarFile); + + VFCArtifactVerificator.verifyNoVfcArtifacts(resourceMetaData, getUser(), null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(artifactsFromFileBeforeUpdate); + } + + @Test + public void importComplexVFCArtifacts_Onboarding_TC1484153() throws Exception { + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + String snmpFile = "Fault-alarms-ASDC-vprobes-vLB.zip"; + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + VendorSoftwareProductObject createVSP = VendorSoftwareProductRestUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), + vendorLicenseModel); + String vspName = createVSP.getName(); + resourceMetaData.setName(vspName); +// VendorSoftwareProductObject resourceMeta = createVSP.right; + String vspid = createVSP.getVspId(); + VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpFile, null, createVSP, getUser()); + VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), createVSP, true); + + String downloadDirectory = getWindowTest().getDownloadDirectory(); + String csarFile = vspid + ".csar"; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUiUtils.importVSP(createVSP); + resourceMetaData.setVersion("0.1"); + + verifyVfcArtifacts(downloadDirectory, csarFile, resourceMetaData, null); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, vnfFile); + + } + + @Test + public void updateComplexVFCArtifacts_AddRemove_Onboarding_TC1484185() throws Exception { + + //check of version is 1 + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + String snmpPollFile = "vprobes-vLB.zip"; + String updatedSnmpPollFile = "vprobes-vLBAgent.zip"; + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + VendorSoftwareProductObject createVSP = VendorSoftwareProductRestUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), + vendorLicenseModel); + String vspName = createVSP.getName(); + resourceMetaData.setName(vspName); + String vspid = createVSP.getVspId(); + String monitoringComponentId = VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpPollFile, null, createVSP, getUser()); + VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), createVSP, true); + + String downloadDirectory = getWindowTest().getDownloadDirectory(); + String csarFile = vspid + ".csar"; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUiUtils.importVSP(createVSP); + ResourceGeneralPage.clickCertifyButton(vspName); + + VendorSoftwareProductRestUtils.updateVspWithVfcArtifacts(filePath, updatedSnmpPollFile, null, monitoringComponentId, getUser(), createVSP); + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUiUtils.updateVSP(createVSP); + resourceMetaData.setVersion("1.1"); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, vnfFile); + + verifyVfcArtifacts(downloadDirectory, csarFile, resourceMetaData, null); + + } + + @Test + public void updateComplexVFCArtifacts_Modify_Onboarding_TC1484195() throws Exception { + + //check of version is 2 + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String vnfFile = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + String snmpFile = "vprobes-vLB.zip"; + String updatedSnmpFile = "vprobes-vLB-Modified.zip"; + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(getUser()); + VendorSoftwareProductObject createVSP = VendorSoftwareProductRestUtils.createVSP(resourceMetaData, vnfFile, filePath, getUser(), + vendorLicenseModel); + String vspName = createVSP.getName(); + resourceMetaData.setName(vspName); + String vspid = createVSP.getVspId(); + String monitoringId = VendorSoftwareProductRestUtils.addVFCArtifacts(filePath, snmpFile, null, createVSP, getUser()); + VendorSoftwareProductRestUtils.prepareVspForUse(getUser(), createVSP, true); + + String downloadDirectory = getWindowTest().getDownloadDirectory(); + String csarFile = vspid + ".csar"; + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUiUtils.importVSP(createVSP); + + Map<String, Object> artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(downloadDirectory + csarFile); + List<String> vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys) { + resourceMetaData.setVersion("0.1"); + VFCArtifactVerificator.setActualVfcArtifactList(key, resourceMetaData, getUser()); + } + + ResourceGeneralPage.clickCertifyButton(vspName); + VendorSoftwareProductRestUtils.updateVspWithVfcArtifacts(filePath, updatedSnmpFile, null, monitoringId, getUser(), createVSP); + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, vspid); + HomePage.showVspRepository(); + OnboardingUiUtils.updateVSP(createVSP); + resourceMetaData.setVersion("1.1"); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, vnfFile); + + Map<String, Object> artifactsFromCsarAfterUpdate = ArtifactFromCsar.getVFCArtifacts(downloadDirectory + csarFile); + List<String> vfcKeysAfterUpdate = artifactsFromCsarAfterUpdate.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeysAfterUpdate) { + verifyVfcInstanceArtifacts(resourceMetaData, null, artifactsFromCsarAfterUpdate, key); + VFCArtifactVerificator.verifyVfcArtifactUpdated(key, resourceMetaData, getUser()); + } + + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + + private Map<String, LinkedList<HeatMetaFirstLevelDefinition>> verifyVfcArtifacts(String filepath, String csarFile, + ResourceReqDetails resourceMetaData, RestResponse getResponse) throws Exception { + + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts"); + Map<String, LinkedList<HeatMetaFirstLevelDefinition>> expectedArtifactMap = null; + ExtentTestActions.log(Status.INFO, "Reading artifacts in CSAR file"); + Map<String, Object> artifactsFromCsar = ArtifactFromCsar.getVFCArtifacts(filepath + csarFile); + List<String> vfcKeys = artifactsFromCsar.keySet().stream().filter(p -> p.contains("vfc")).collect(Collectors.toList()); + for (String key : vfcKeys) { + expectedArtifactMap = verifyVfcInstanceArtifacts(resourceMetaData, getResponse, artifactsFromCsar, key); + } + return expectedArtifactMap; + } + + private Map<String, LinkedList<HeatMetaFirstLevelDefinition>> verifyVfcInstanceArtifacts( + ResourceReqDetails resourceMetaData, RestResponse getResponse, Map<String, Object> artifactsFromCsar, String key) { + + Map<String, LinkedList<HeatMetaFirstLevelDefinition>> expectedArtifactMap; + Map<String, LinkedList<HeatMetaFirstLevelDefinition>> vfcDeploymentArtifacts = (Map<String, LinkedList<HeatMetaFirstLevelDefinition>>) artifactsFromCsar.get(key); + LinkedList<HeatMetaFirstLevelDefinition> deploymentList = vfcDeploymentArtifacts.get(DEPLOYMENT); + LinkedList<HeatMetaFirstLevelDefinition> informationalList = (LinkedList<HeatMetaFirstLevelDefinition>) vfcDeploymentArtifacts.get(INFORMATIONAL); + + expectedArtifactMap = new HashMap<String, LinkedList<HeatMetaFirstLevelDefinition>>(); + if (deploymentList == null) { + expectedArtifactMap.put(DEPLOYMENT_ARTIFACTS, new LinkedList<HeatMetaFirstLevelDefinition>()); + } else { + expectedArtifactMap.put(DEPLOYMENT_ARTIFACTS, deploymentList); + } + if (informationalList == null) { + expectedArtifactMap.put(ARTIFACTS, new LinkedList<HeatMetaFirstLevelDefinition>()); + } else { + expectedArtifactMap.put(ARTIFACTS, informationalList); + } + + VFCArtifactVerificator.verifyVfcArtifacts(resourceMetaData, getUser(), key, expectedArtifactMap, getResponse); + return expectedArtifactMap; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Vf.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Vf.java new file mode 100644 index 0000000000..d84ee63455 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/Vf.java @@ -0,0 +1,522 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfModuleVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ToscaArtifactsPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class Vf extends SetupCDTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(Vf.class); + + private String filePath; + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath(""); + } + + @BeforeMethod + public void beforeTest() { + System.out.println("File repository is : " + filePath); + getExtendTest().log(Status.INFO, "File repository is : " + filePath); + } + + + @Test + public void vfcLinkedToComputeInVfFlow() throws Exception { + String fileName = "vFW_VFC2.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try { + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCertifyButton(atomicResourceMetaData.getName()); + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(String.format("%s %s", DataTestIdEnum.LeftPanelCanvasItems.COMPUTE.getValue(), "1.0")); + CanvasElement computeElement = canvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement cpElement = canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + AssertJUnit.assertNotNull(cpElement); + ServiceVerificator.verifyNumOfComponentInstances(vfMetaData, "0.1", 2, getUser()); + + canvasManager.linkElements(computeElement.getElementNameOnCanvas(), cpElement.getElementNameOnCanvas()); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyLinkCreated(vfMetaData, getUser(), 1); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + @Test + public void addUpdateDeleteDeploymentArtifactToVfTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.clickEditArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.artifactPopup().insertDescription(newDescription); + DeploymentArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + AssertJUnit.assertTrue("artifact " + deploymentArtifactList.get(0).getArtifactLabel() + "is not deleted", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size() - 1)); + + AssertJUnit.assertTrue("artifact " + deploymentArtifactList.get(1).getArtifactLabel() + "is not displayed", DeploymentArtifactPage.clickOnArtifactDescription(deploymentArtifactList.get(1).getArtifactLabel()).isDisplayed()); + } + + + @Test + public void addUpdateDeleteInformationalArtifact() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", InformationalArtifactPage.checkElementsCountInTable(1)); + + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifact.getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + AssertJUnit.assertTrue("artifact " + informationalArtifact.getArtifactLabel() + "is not deleted", InformationalArtifactPage.checkElementsCountInTable(0)); + } + + + @Test + public void addPropertiesToVfcInstanceInVfTest() throws Exception { + + if (true) { +// throw new SkipException("Open bug 373762, can't update properties on CP or VFC instance on Composition screen"); + SetupCDTest.getExtendTest().log(Status.INFO, "Open bug 373762, can't update properties on CP or VFC instance on Composition screen"); + } + + String fileName = "vFW_VFC.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try { + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + vfCanvasManager.clickOnCanvaElement(vfcElement); + CompositionPage.showPropertiesAndAttributesTab(); + List<WebElement> properties = CompositionPage.getProperties(); + String propertyValue = "abc123"; + for (int i = 0; i < 2; i++) { + WebElement findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label")); + findElement.click(); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue); + PropertiesPage.getPropertyPopup().clickSave(); + + + findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-value")); + AssertJUnit.assertTrue(findElement.getText().equals(propertyValue)); + } + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void changeInstanceVersionTest() throws Exception { + + ResourceReqDetails atomicResourceMetaData = null; + ResourceReqDetails vfMetaData = null; + CanvasManager vfCanvasManager; + CanvasElement vfcElement = null; + String fileName = "vFW_VFC3.yml"; + try { + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + CompositionPage.clickCertifyButton(vfMetaData.getName()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + AssertJUnit.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "1.0"); + + //verfication + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "1.0"); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + + @Test + public void addAllInformationalArtifactPlaceholdersInVfTest() throws Exception { + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VF, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + for (DataTestIdEnum.InformationalArtifactsPlaceholders informArtifact : DataTestIdEnum.InformationalArtifactsPlaceholders.values()) { + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(informArtifact, filePath, "asc_heat 0 2.yaml", informArtifact.getValue()); + } + + AssertJUnit.assertTrue(InformationalArtifactPage.checkElementsCountInTable(DataTestIdEnum.InformationalArtifactsPlaceholders.values().length)); + } + + @Test + public void verifyToscaArtifactsExist() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + final int numOfToscaArtifacts = 2; + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + AssertJUnit.assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); + + for (int i = 0; i < numOfToscaArtifacts; i++) { + String typeFromScreen = ToscaArtifactsPage.getArtifactType(i); + AssertJUnit.assertTrue(typeFromScreen.equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) || typeFromScreen.equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())); + } + ToscaArtifactsPage.clickCertifyButton(vfMetaData.getName()); + VfVerificator.verifyToscaArtifactsInfo(vfMetaData, getUser()); + } + + @Test + public void vfCertificationTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + String vfName = vfMetaData.getName(); + + ResourceGeneralPage.clickCheckinButton(vfName); + GeneralUIUtils.findComponentAndClick(vfName); + ResourceGeneralPage.clickCertifyButton(vfName); + + vfMetaData.setVersion("1.0"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.CERTIFIED); + + GeneralUIUtils.findComponentAndClick(vfName); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void deleteVfCheckedoutTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + GeneralPageElements.clickTrashButtonAndConfirm(); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyVfDeleted(vfMetaData, getUser()); + } + + @Test + public void revertVfMetadataTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceReqDetails vfRevertDetails = new ResourceReqDetails(); + vfRevertDetails.setName("ciUpdatedName"); + vfRevertDetails.setDescription("kuku"); + vfRevertDetails.setCategories(vfMetaData.getCategories()); + vfRevertDetails.setVendorName("updatedVendor"); + vfRevertDetails.setVendorRelease("updatedRelease"); + ResourceUIUtils.fillResourceGeneralInformationPage(vfRevertDetails, getUser(), false); + + GeneralPageElements.clickRevertButton(); + + VfVerificator.verifyVFMetadataInUI(vfMetaData); + + } + + @Test + public void addDeploymentArtifactInCompositionScreenTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3", "OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className("i-sdc-designer-sidebar-section-content-item-artifact")); + AssertJUnit.assertEquals(1, actualArtifactList.size()); + } + + // future removed from ui + + @Test + public void addDeploymentArtifactAndVerifyInCompositionScreen() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + ArtifactInfo deploymentArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + AssertJUnit.assertTrue(DeploymentArtifactPage.checkElementsCountInTable(1)); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showDeploymentArtifactTab(); + List<WebElement> deploymentArtifactsFromScreen = CompositionPage.getDeploymentArtifacts(); + AssertJUnit.assertTrue(1 == deploymentArtifactsFromScreen.size()); + + String actualArtifactFileName = deploymentArtifactsFromScreen.get(0).getText(); + AssertJUnit.assertTrue("asc_heat-0-2.yaml".equals(actualArtifactFileName)); + } + + @Test + public void checkoutVfTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + + vfMetaData.setVersion("0.2"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + ResourceGeneralPage.clickCertifyButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + vfMetaData.setVersion("1.1"); + vfMetaData.setUniqueId(null); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + } + + @Test + public void deleteInstanceFromVfCanvas() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + CanvasElement portElement = vfCanvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.PORT); + + vfCanvasManager.clickOnCanvaElement(computeElement); + vfCanvasManager.deleteElementFromCanvas(computeElement); + + VfVerificator.verifyNumOfComponentInstances(vfMetaData, 1, getUser()); + } + + @Test + public void changeInstanceNameInVfTest() throws Exception { + final ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + Resource containerObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vfMetaData.getName(), vfMetaData.getVersion()); + Resource computeObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, "Compute", "1.0"); + ComponentInstance componentInstanceDetails = AtomicOperationUtils.addComponentInstanceToComponentContainer(computeObject, containerObject, UserRoleEnum.DESIGNER, true).left().value(); + containerObject = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vfMetaData.getName(), vfMetaData.getVersion()); + String intanceWithUpdatedName = AtomicOperationUtils.updateComponentInstanceName("newName", containerObject, componentInstanceDetails.getName(), getUser(), true).getRight().getName(); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + assertEquals(intanceWithUpdatedName, "newName"); + } + + @Test + public void submitVfForTestingWithNonCertifiedAsset() throws Exception { + String fileName = "vFW_VFC4.yml"; + + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickCheckinButton(atomicResourceMetaData.getName()); + + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + try { + CompositionPage.clickCertifyButton(vfMetaData.getName()); + assert (false); + } catch (Exception e) { + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + AssertJUnit.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + + @Test + public void isDisabledAndReadOnlyInCheckin() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + DataTestIdEnum.ResourceMetadataEnum[] fieldsForCheck = {DataTestIdEnum.ResourceMetadataEnum.RESOURCE_NAME, + DataTestIdEnum.ResourceMetadataEnum.DESCRIPTION, DataTestIdEnum.ResourceMetadataEnum.VENDOR_NAME, DataTestIdEnum.ResourceMetadataEnum.VENDOR_RELEASE, + DataTestIdEnum.ResourceMetadataEnum.CONTACT_ID}; + + for (DataTestIdEnum.ResourceMetadataEnum field : fieldsForCheck) { + AssertJUnit.assertTrue(GeneralUIUtils.isElementReadOnly(field.getValue())); + } + + AssertJUnit.assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.ResourceMetadataEnum.CATEGORY.getValue())); + AssertJUnit.assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue())); + } + + @Test + public void exportToscaWithModulePropertiesVFTest() throws Exception { + String vnfFile = "1-Vf-zrdm5bpxmc02-092017-(MOBILITY)_v2.0.zip"; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource();//getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser()); + String vspName = vendorSoftwareProductObject.getName(); + ResourceGeneralPage.clickSubmitForTestingButton(vspName); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + VfModuleVerificator.validateSpecificModulePropertiesFromRequest(resource); + } + + @Test + public void canvasTestJS() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = canvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + CanvasElement portElement = canvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.PORT); + + canvasManager.linkElements(computeElement.getElementNameOnCanvas(), portElement.getElementNameOnCanvas()); + + } + + private void takeScreenshot(final String screenshotName, final String errorMsg) { + try { + ExtentTestActions.addScreenshot(Status.ERROR, screenshotName, errorMsg); + } catch (final IOException e) { + LOGGER.warn("Could not take screenshot", e); + } + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfAPI.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfAPI.java new file mode 100644 index 0000000000..2631033a8c --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfAPI.java @@ -0,0 +1,776 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.NormativeTypesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser; +import org.onap.sdc.frontend.ci.tests.verificator.ServiceVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfModuleVerificator; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Resource; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.AttFtpClient; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.InputsPage; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.pages.ToscaArtifactsPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.onap.sdc.frontend.ci.tests.utilities.PropertiesUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.AssertJUnit; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class VfAPI extends SetupCDTest { + + private String filePath; + + @BeforeClass + public void beforeClass() { + filePath = FileHandling.getFilePath(""); + } + + @BeforeMethod + public void beforeTest() { + System.out.println("File repository is : " + filePath); + getExtendTest().log(Status.INFO, "File repository is : " + filePath); + } + + private ResourceReqDetails createVFviaAPI() { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating VF %s", vfMetaData.getName())); + AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value(); + return vfMetaData; + } + + + @Test + public void updateVF() throws Exception { + + // create Resource + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(resourceMetaData, getUser()); + + // update Resource + ResourceReqDetails updatedResource = new ResourceReqDetails(); + updatedResource.setName(ElementFactory.getResourcePrefix() + "UpdatedName" + resourceMetaData.getName()); + updatedResource.setDescription("kuku"); + updatedResource.setVendorName("updatedVendor"); + updatedResource.setVendorRelease("updatedRelease"); + updatedResource.setContactId("ab0001"); + updatedResource.setCategories(resourceMetaData.getCategories()); + updatedResource.setVersion("0.1"); + updatedResource.setResourceType(ResourceTypeEnum.VF.getValue()); + List<String> newTags = resourceMetaData.getTags(); + newTags.remove(resourceMetaData.getName()); + newTags.add(updatedResource.getName()); + updatedResource.setTags(newTags); + ResourceUIUtils.updateResource(updatedResource, getUser()); + + VfVerificator.verifyVFMetadataInUI(updatedResource); + VfVerificator.verifyVFUpdated(updatedResource, getUser()); + } + + + @Test + public void vfcLinkedToComputeInVfFlowApi() throws Exception { + String fileName = "vFW_VFC2.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try { + //Create VFC via API + Resource vfc = AtomicOperationUtils.importResource(filePath, fileName).left().value(); + atomicResourceMetaData.setName(vfc.getName()); + + //Certify VFC via API + vfc = (Resource) AtomicOperationUtils.changeComponentState(vfc, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //Create VF via API + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + //Composition - drag the created VFC and another element, link between them + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(String.format("%s %s", DataTestIdEnum.LeftPanelCanvasItems.COMPUTE.getValue(), "1.0")); + CanvasElement computeElement = canvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement cpElement = canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + AssertJUnit.assertNotNull(cpElement); + ServiceVerificator.verifyNumOfComponentInstances(vfMetaData, "0.1", 2, getUser()); + canvasManager.linkElements(cpElement, computeElement); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyLinkCreated(vfMetaData, getUser(), 1); + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + } + + + @Test + public void addUpdateDeleteDeploymentArtifactToVfTestApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + List<ArtifactInfo> deploymentArtifactList = new ArrayList<ArtifactInfo>(); + deploymentArtifactList.add(new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER")); + deploymentArtifactList.add(new ArtifactInfo(filePath, "sample-xml-alldata-1-1.xml", "cuku", "artifact2", "YANG_XML")); + for (ArtifactInfo deploymentArtifact : deploymentArtifactList) { + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + } + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size())); + + String newDescription = "new description"; + DeploymentArtifactPage.clickEditArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.artifactPopup().insertDescription(newDescription); + DeploymentArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = DeploymentArtifactPage.getArtifactDescription(deploymentArtifactList.get(0).getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + DeploymentArtifactPage.clickDeleteArtifact(deploymentArtifactList.get(0).getArtifactLabel()); + DeploymentArtifactPage.clickOK(); + AssertJUnit.assertTrue("artifact " + deploymentArtifactList.get(0).getArtifactLabel() + "is not deleted", DeploymentArtifactPage.checkElementsCountInTable(deploymentArtifactList.size() - 1)); + + AssertJUnit.assertTrue("artifact " + deploymentArtifactList.get(1).getArtifactLabel() + "is not displayed", DeploymentArtifactPage.clickOnArtifactDescription(deploymentArtifactList.get(1).getArtifactLabel()).isDisplayed()); + } + + + @Test + public void addUpdateDeleteInformationalArtifactApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + + ArtifactInfo informationalArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + InformationalArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(informationalArtifact); + + AssertJUnit.assertTrue("artifact table does not contain artifacts uploaded", InformationalArtifactPage.checkElementsCountInTable(1)); + + String newDescription = "new description"; + InformationalArtifactPage.clickEditArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.artifactPopup().insertDescription(newDescription); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + String actualArtifactDescription = InformationalArtifactPage.getArtifactDescription(informationalArtifact.getArtifactLabel()); + AssertJUnit.assertTrue("artifact description is not updated", newDescription.equals(actualArtifactDescription)); + + InformationalArtifactPage.clickDeleteArtifact(informationalArtifact.getArtifactLabel()); + InformationalArtifactPage.clickOK(); + AssertJUnit.assertTrue("artifact " + informationalArtifact.getArtifactLabel() + "is not deleted", InformationalArtifactPage.checkElementsCountInTable(0)); + } + + + @Test + public void addPropertiesToVfcInstanceInVfTestApi() throws Exception { + + String fileName = "vFW_VFC.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + try { + //Create VFC via API + Resource vfc = AtomicOperationUtils.importResource(filePath, fileName).left().value(); + atomicResourceMetaData.setName(vfc.getName()); + + //Certify VFC via API + vfc = (Resource) AtomicOperationUtils.changeComponentState(vfc, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + CanvasElement vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + vfCanvasManager.clickOnCanvaElement(vfcElement); + CompositionPage.showPropertiesAndAttributesTab(); + List<WebElement> properties = CompositionPage.getProperties(); + String propertyValue = "abc123"; + for (int i = 0; i < 2; i++) { + WebElement findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-and-attribute-label")); + findElement.click(); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue); + PropertiesPage.getPropertyPopup().clickSave(); + + + findElement = properties.get(i).findElement(By.className("i-sdc-designer-sidebar-section-content-item-property-value")); + AssertJUnit.assertTrue(findElement.getText().equals(propertyValue)); + } + } finally { + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + } + +/* @Test + public void changeInstanceVersionTest() throws Exception{ + + ResourceReqDetails atomicResourceMetaData = null; + ResourceReqDetails vfMetaData = null; + CanvasManager vfCanvasManager; + CanvasElement vfcElement = null; + String fileName = "vFW_VFC3.yml"; + try{ + atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + ResourceUIUtils.importVfc(atomicResourceMetaData, filePath, fileName, getUser()); + ResourceGeneralPage.clickSubmitForTestingButton(atomicResourceMetaData.getName()); + + vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + vfcElement = vfCanvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + + CompositionPage.clickSubmitForTestingButton(vfMetaData.getName()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + AssertJUnit.assertTrue(errorMessage.contains(checkUIResponseOnError)); + + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(atomicResourceMetaData.getName()); + TesterOperationPage.certifyComponent(atomicResourceMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + vfCanvasManager = CanvasManager.getCanvasManager(); + CompositionPage.changeComponentVersion(vfCanvasManager, vfcElement, "1.0"); + + //verification + VfVerificator.verifyInstanceVersion(vfMetaData, getUser(), atomicResourceMetaData.getName(), "1.0"); + } + + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "1.0"); + } + + }*/ + + // future removed from ui + @Test(enabled = true) + public void addUpdateDeleteSimplePropertiesToVfTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToPropertiesScreen(); + List<PropertyTypeEnum> propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = PropertiesPage.getElemenetsFromTable().size(); + for (PropertyTypeEnum prop : propertyList) { + PropertiesUIUtils.addNewProperty(prop); + } + AssertJUnit.assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> PropertiesPage.getElemenetsFromTable())); + VfVerificator.verifyPropertiesInUI(propertyList); + PropertiesPage.verifyTotalProperitesField(propertiesCount + propertyList.size()); + + + PropertyTypeEnum prop = propertyList.get(0); + prop.setDescription("updatedDescription"); + prop.setValue("value"); + PropertiesUIUtils.updateProperty(prop); + + PropertiesPage.clickDeletePropertyArtifact(prop.getName()); + AssertJUnit.assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size() - 1, () -> PropertiesPage.getElemenetsFromTable())); + } + + // future removed from ui + @Test(enabled = true) + public void vfcInstancesInputScreenTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + + Map<String, String> elementsIntancesMap = new HashMap<String, String>(); + for (DataTestIdEnum.LeftPanelCanvasItems element : Arrays.asList(DataTestIdEnum.LeftPanelCanvasItems.DATABASE, DataTestIdEnum.LeftPanelCanvasItems.BLOCK_STORAGE)) { + CanvasElement elementOnCanvas = vfCanvasManager.createElementOnCanvas(element); + vfCanvasManager.clickOnCanvaElement(elementOnCanvas); + String selectedInstanceName = CompositionPage.getSelectedInstanceName(); + elementsIntancesMap.put(selectedInstanceName, element.getValue()); + } + + CompositionPage.moveToInputsScreen(); + int canvasElementsSize = vfCanvasManager.getCanvasElements().size(); + AssertJUnit.assertTrue("Instances count is not as expected: " + canvasElementsSize, InputsPage.checkElementsCountInTable(canvasElementsSize)); + + for (String element : elementsIntancesMap.keySet()) { + String resourceName = elementsIntancesMap.get(element); + ResourceReqDetails resource = new ResourceReqDetails(); + resource.setName(resourceName); + resource.setVersion("1.0"); + resource.setResourceType(ResourceTypeEnum.VFC.toString()); + RestResponse restResponse = RestCDUtils.getResource(resource, getUser()); + Map<String, String> propertiesNameTypeJson = ResponseParser.getPropertiesNameType(restResponse); + + List<WebElement> propertyRowsFromTable = InputsPage.getInstancePropertiesList(element); + AssertJUnit.assertTrue("Some properties are missing in table. Instance name is : " + element, propertyRowsFromTable.size() == propertiesNameTypeJson.size()); + VfVerificator.verifyVfInputs(element, propertiesNameTypeJson, propertyRowsFromTable); + + GeneralUIUtils.clickOnElementByText(element); + } + + } + + + @Test + public void addAllInformationalArtifactPlaceholdersInVfTestApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + int fileNameCounter = 0; + String fileName; + for (DataTestIdEnum.InformationalArtifactsPlaceholders informArtifact : DataTestIdEnum.InformationalArtifactsPlaceholders.values()) { + fileName = HEAT_FILE_YAML_NAME_PREFIX + fileNameCounter + HEAT_FILE_YAML_NAME_SUFFIX; + ArtifactUIUtils.fillPlaceHolderInformationalArtifact(informArtifact, + FileHandling.getFilePath("uniqueFileNames"), fileName, + informArtifact.getValue()); + fileNameCounter++; + } + assertThat(InformationalArtifactPage.checkElementsCountInTable(DataTestIdEnum.InformationalArtifactsPlaceholders.values().length)).isTrue(); + } + + @Test + public void verifyToscaArtifactsExistApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + final int numOfToscaArtifacts = 2; + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + AssertJUnit.assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); + + for (int i = 0; i < numOfToscaArtifacts; i++) { + String typeFromScreen = ToscaArtifactsPage.getArtifactType(i); + AssertJUnit.assertTrue(typeFromScreen.equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) || typeFromScreen.equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())); + } + + //TODO Andrey should click on certify button + ToscaArtifactsPage.clickCertifyButton(vfMetaData.getName()); + vfMetaData.setVersion("1.0"); + VfVerificator.verifyToscaArtifactsInfo(vfMetaData, getUser()); + } + + @Test(enabled = true) + public void testDownload() throws Exception { +// ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); +// ResourceUIUtils.createResource(vfMetaData, getUser()); +// +// final int numOfToscaArtifacts = 2; +// ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); +// assertTrue(ToscaArtifactsPage.checkElementsCountInTable(numOfToscaArtifacts)); +// GeneralUIUtils.clickOnElementByTestId("download-Tosca Model"); +// System.out.println("download me"); + + AttFtpClient attFtpClient = AttFtpClient.getFtpClient(); + + File retrieveLastModifiedFileFromFTP = attFtpClient.retrieveLastModifiedFileFromFTP(); + attFtpClient.deleteFilesFromFTPserver(); + } + + @Test + public void vfCertificationTestApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + Resource vf = AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value(); + + //Certify VF via API + vf = (Resource) AtomicOperationUtils.changeComponentState(vf, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CERTIFIED); + } + + @Test + public void deleteVfCheckedoutTestApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + GeneralPageElements.clickTrashButtonAndConfirm(); + + vfMetaData.setVersion("0.1"); + VfVerificator.verifyVfDeleted(vfMetaData, getUser()); + } + + @Test + public void revertVfMetadataTestApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceReqDetails vfRevertDetails = new ResourceReqDetails(); + vfRevertDetails.setName("ciUpdatedName"); + vfRevertDetails.setDescription("kuku"); + vfRevertDetails.setCategories(vfMetaData.getCategories()); + vfRevertDetails.setVendorName("updatedVendor"); + vfRevertDetails.setVendorRelease("updatedRelease"); + ResourceUIUtils.fillResourceGeneralInformationPage(vfRevertDetails, getUser(), false); + + GeneralPageElements.clickRevertButton(); + + VfVerificator.verifyVFMetadataInUI(vfMetaData); + + } + + @Test + public void addDeploymentArtifactInCompositionScreenTestApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + ArtifactInfo artifact = new ArtifactInfo(filePath, "Heat-File.yaml", "kuku", "artifact3", "OTHER"); + CompositionPage.showDeploymentArtifactTab(); + CompositionPage.clickAddArtifactButton(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(artifact, CompositionPage.artifactPopup()); + + List<WebElement> actualArtifactList = GeneralUIUtils.getWebElementsListBy(By.className("i-sdc-designer-sidebar-section-content-item-artifact")); + AssertJUnit.assertEquals(1, actualArtifactList.size()); + } + + // future removed from ui + @Test(enabled = true) + public void addPropertyInCompositionScreenTest() throws Exception { + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showPropertiesAndAttributesTab(); + List<PropertyTypeEnum> propertyList = Arrays.asList(PropertyTypeEnum.STRING, PropertyTypeEnum.INTEGER); + int propertiesCount = CompositionPage.getProperties().size(); + for (PropertyTypeEnum prop : propertyList) { + PropertiesUIUtils.addNewProperty(prop); + } + AssertJUnit.assertTrue(GeneralUIUtils.checkElementsCountInTable(propertiesCount + propertyList.size(), () -> CompositionPage.getProperties())); + } + + @Test + public void addDeploymentArtifactAndVerifyInCompositionScreenApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + ArtifactInfo deploymentArtifact = new ArtifactInfo(filePath, "asc_heat 0 2.yaml", "kuku", "artifact1", "OTHER"); + DeploymentArtifactPage.clickAddNewArtifact(); + ArtifactUIUtils.fillAndAddNewArtifactParameters(deploymentArtifact); + AssertJUnit.assertTrue(DeploymentArtifactPage.checkElementsCountInTable(1)); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + CompositionPage.showDeploymentArtifactTab(); + List<WebElement> deploymentArtifactsFromScreen = CompositionPage.getDeploymentArtifacts(); + AssertJUnit.assertTrue(1 == deploymentArtifactsFromScreen.size()); + + String actualArtifactFileName = deploymentArtifactsFromScreen.get(0).getText(); + AssertJUnit.assertTrue("asc_heat-0-2.yaml".equals(actualArtifactFileName)); + } + + /*@Test + public void checkoutVfTest() throws Exception{ + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.createVF(vfMetaData, getUser()); + + ResourceGeneralPage.clickCheckinButton(vfMetaData.getName()); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + GeneralPageElements.clickCheckoutButton(); + + vfMetaData.setVersion("0.2"); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + + ResourceGeneralPage.clickSubmitForTestingButton(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.TESTER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + TesterOperationPage.certifyComponent(vfMetaData.getName()); + + reloginWithNewRole(UserRoleEnum.DESIGNER); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + ResourceGeneralPage.clickCheckoutButton(); + + vfMetaData.setVersion("1.1"); + vfMetaData.setUniqueId(null); + VfVerificator.verifyVFLifecycle(vfMetaData, getUser(), LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT); + VfVerificator.verifyVfLifecycleInUI(LifeCycleStateEnum.CHECKOUT); + }*/ + + @Test + public void deleteInstanceFromVfCanvasApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + vfCanvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.PORT); + + vfCanvasManager.clickOnCanvaElement(computeElement); + vfCanvasManager.deleteElementFromCanvas(computeElement); + + VfVerificator.verifyNumOfComponentInstances(vfMetaData, 1, getUser()); + } + + @Test + public void changeInstanceNameInVfTestApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = createVFviaAPI(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager vfCanvasManager = CanvasManager.getCanvasManager(); + CanvasElement computeElement = vfCanvasManager.createElementOnCanvas(DataTestIdEnum.LeftPanelCanvasItems.COMPUTE); + + String updatedInstanceName = "updatedName"; + vfCanvasManager.updateElementNameInCanvas(computeElement, updatedInstanceName); + + String actualSelectedInstanceName = CompositionPage.getSelectedInstanceName(); + AssertJUnit.assertTrue(updatedInstanceName.equals(actualSelectedInstanceName)); + } + + + /*@Test + public void submitVfForTestingWithNonCertifiedAssetApi() throws Exception{ + String fileName = "vFW_VFC4.yml"; + ResourceReqDetails atomicResourceMetaData = ElementFactory.getDefaultResourceByTypeNormTypeAndCatregory(ResourceTypeEnum.VFC, NormativeTypesEnum.ROOT, ResourceCategoryEnum.NETWORK_L2_3_ROUTERS, getUser()); + + //Create VFC via API + Resource vfc = AtomicOperationUtils.importResource(filePath, fileName).left().value(); + atomicResourceMetaData.setName(vfc.getName()); + + //Submit VFC for testing via API + vfc = (Resource) AtomicOperationUtils.changeComponentState(vfc, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFICATIONREQUEST, true).getLeft(); + + //Create VF via API + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + DeploymentArtifactPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + CompositionPage.searchForElement(atomicResourceMetaData.getName()); + canvasManager.createElementOnCanvas(atomicResourceMetaData.getName()); + + try{ + //TODO Andrey should click on certify button + CompositionPage.clickCertifyButton(vfMetaData.getName()); + assert(false); + } + catch(Exception e){ + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.VALIDATED_RESOURCE_NOT_FOUND.name()); + AssertJUnit.assertTrue(errorMessage.contains(checkUIResponseOnError)); + } + finally{ + ResourceRestUtils.deleteResourceByNameAndVersion(atomicResourceMetaData.getName(), "0.1"); + } + }*/ + + @Test + public void isDisabledAndReadOnlyInCheckinApi() throws Exception { + //Create VF via API + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + Resource vf = AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value(); + + //Check in VF via API + vf = (Resource) AtomicOperationUtils.changeComponentState(vf, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + //Go to Catalog and find the created VF + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + DataTestIdEnum.ResourceMetadataEnum[] fieldsForCheck = {DataTestIdEnum.ResourceMetadataEnum.RESOURCE_NAME, + DataTestIdEnum.ResourceMetadataEnum.DESCRIPTION, DataTestIdEnum.ResourceMetadataEnum.VENDOR_NAME, DataTestIdEnum.ResourceMetadataEnum.VENDOR_RELEASE, + DataTestIdEnum.ResourceMetadataEnum.CONTACT_ID}; + + for (DataTestIdEnum.ResourceMetadataEnum field : fieldsForCheck) { + AssertJUnit.assertTrue(GeneralUIUtils.isElementReadOnly(field.getValue())); + } + + AssertJUnit.assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.ResourceMetadataEnum.CATEGORY.getValue())); + AssertJUnit.assertTrue(GeneralUIUtils.isElementDisabled(DataTestIdEnum.LifeCyleChangeButtons.CREATE.getValue())); + } + + @Test + public void displayHomeAfterNavigationToOnboardingTest() throws Exception { + //Production bug scenario: "Home" - Click on any VF/ Service - Copy the URL - Go to “ONBOARD” - Paste the URL - Review the breadcrumbs + // Expected: "Home" Actual: "Onboarding" + + //Create VF via API + ResourceReqDetails vfMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + Resource vf = AtomicOperationUtils.createResourceByResourceDetails(vfMetaData, UserRoleEnum.DESIGNER, true).left().value(); + + //Check in VF via API + vf = (Resource) AtomicOperationUtils.changeComponentState(vf, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CHECKIN, true).getLeft(); + + //Find the created VF on Home page + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + HomePage.navigateToHomePage(); + GeneralUIUtils.findComponentAndClick(vfMetaData.getName()); + + //Copy current URL, navigate to OB screen and paste URL + String url = GeneralUIUtils.copyCurrentURL(); + CompositionPage.moveToOnboardScreen(); + GeneralUIUtils.navigateToURL(url); + GeneralUIUtils.ultimateWait(); + + //Validate that main menu button is Home and not Onboarding + String id = DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue(); + WebElement button = GeneralUIUtils.getWebElementByTestID(id); + AssertJUnit.assertTrue(button.getAttribute("text").trim().equals("HOME")); + } + + @Test + public void exportToscaWithModulePropertiesVFTest() throws Exception { + String vnfFile = "1-Vf-zrdm5bpxmc02-092017-(MOBILITY)_v2.0.zip"; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser()); + String vspName = vsp.getName(); + ResourceGeneralPage.clickCertifyButton(vspName); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "1.0"); + VfModuleVerificator.validateSpecificModulePropertiesFromRequest(resource); + } + + @Test + public void exportToscaWithModulePropertiesTemplateCheckVFTest() throws Exception { + String vnfFile = "1-Vf-zrdm5bpxmc02-092017-(MOBILITY)_v2.0.zip"; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + OnboardingUiUtils.onboardAndValidate(resourceReqDetails, FileHandling.getVnfRepositoryPath(), vnfFile, getUser()); + ResourceGeneralPage.getLeftMenu().moveToToscaArtifactsScreen(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.TOSCA_MODEL.getValue()); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(latestFilefromDir); + VfModuleVerificator.validateSpecificModulePropertiesFromFile(toscaDefinition); + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfArtifacts.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfArtifacts.java new file mode 100644 index 0000000000..412c2a5ec6 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfArtifacts.java @@ -0,0 +1,405 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.businesslogic.ArtifactBusinessLogic; +import org.onap.sdc.backend.ci.tests.config.Config; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.HeatWithParametersDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.openecomp.sdc.be.model.ArtifactDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.HomeUtils; +import org.onap.sdc.frontend.ci.tests.utilities.OnboardingUiUtils; +import org.openqa.selenium.WebElement; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static org.testng.AssertJUnit.assertTrue; + +public class VfArtifacts extends SetupCDTest { + + public static final String VSAEGW_FDNT_30_1607_E2E_ZIP = "2016-043_vsaegw_fdnt_30_1607_e2e.zip"; + public static final String VFW_FCGI_30_1607_E2E_ZIP = "2016-044_vfw_fcgi_30_1607_e2e.zip"; + public static final String FDNT_UPDATE_HEAT_PARAMS_ZIP = "FDNT_UpdateHeatParams.zip"; + public static final String FDNT_WITHOUT_ENV_FILES_ZIP = "FDNT_WithoutEnvFiles.zip"; + public static final String VLANDSLIDE_LDSA_30_1607_E2E_ZIP = "2016-014_vlandslide_ldsa_30_1607_e2e.zip"; + public static final String VJSA_VJSA_30_1610_E2E_ZIP = "2016-209_vjsa_vjsa_30_1610_e2e.zip"; + public static final String VLB_LMSP_30_1607_E2E_ZIP = "2016-045_vlb_lmsp_30_1607_e2e.zip"; + public static final String MOBT_MOBT_30_1607_E2E_ZIP = "2016-109_mobt_mobt_30_1607_e2e.zip"; + public static final String MOBT_MOBT_30_1607_E2E_DIFFERENT_PARAMS_ZIP = "2016-109_mobt_mobt_30_1607_e2e_DifferentParams.zip"; + public static final String VMSP_PXMC_30_1607_E2E_ZIP = "2016-042_vmsp_pxmc_30_1607_e2e.zip"; + public static final String VFW_FNAT_30_1607_E2E_ZIP = "2016-044_vfw_fnat_30_1607_e2e.zip"; + public static final String VLANDSLIDE_LDST_30_1607_E2E_ZIP = "2016-014_vlandslide_ldst_30_1607_e2e.zip"; + public static final String VIXIA_IXLA_30_1607_E2E_ZIP = "2016-017_vixia_ixla_30_1607_e2e.zip"; + private String filePath; + private String vnfsRepositoryPath; + private String createdEnvFilePath; + private static final String PARAMETERS = "parameters"; + + @BeforeMethod + public void beforeTest() throws FileNotFoundException { + filePath = getWindowTest().getDownloadDirectory(); + vnfsRepositoryPath = FileHandling.getFilePath("VfArtifacts"); + Config config = Utils.getConfig(); + createdEnvFilePath = config.getDownloadAutomationFolder(); + } + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + + + @DataProvider(name = "heatEnvAndVersion", parallel = false) +// parameters: VSP, updatedVsp, expectedHeatVersion, expectedHeatEnvVersion + public Object[][] provideData() { + + return new Object[][]{ + {VSAEGW_FDNT_30_1607_E2E_ZIP, FDNT_UPDATE_HEAT_PARAMS_ZIP, "2", "2"}, // expected heat version 2 and heatEnv 2 + {VSAEGW_FDNT_30_1607_E2E_ZIP, FDNT_WITHOUT_ENV_FILES_ZIP, "1", "2"}, // expected heat version 1 and heatEnv 2 + {VLANDSLIDE_LDSA_30_1607_E2E_ZIP, VJSA_VJSA_30_1610_E2E_ZIP, "1", "1"}, // expected heat version 1 and heatEnv 1 + {VLB_LMSP_30_1607_E2E_ZIP, VLB_LMSP_30_1607_E2E_ZIP, "1", "2"}, // expected heat version 1 and heatEnv 2(DE270634) + {MOBT_MOBT_30_1607_E2E_ZIP, MOBT_MOBT_30_1607_E2E_DIFFERENT_PARAMS_ZIP, "2", "2"} // expected heat version 2 and heatEnv 2 + }; + } + + // update first env file and verify parameters value + @Test + public void uploadUpdatedHeatEnv() throws Exception { + + String vnfFile = VFW_FNAT_30_1607_E2E_ZIP; + File updateEnvFile = null; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.getName(); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts(); + List<HeatWithParametersDefinition> envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); +// create env file and update it + if (envFilesList.size() > 0) { +// select index of env file to be updated + HeatWithParametersDefinition selectedEnvFileToUpdate = envFilesList.get(0); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + selectedEnvFileToUpdate.getHeatEnvLabel()); + updateEnvFile = ArtifactUIUtils.uploadCreatedUpdateParametersEnvFile(selectedEnvFileToUpdate, createdEnvFilePath); + ArtifactUIUtils.verifyUpdatedEnvParameters(selectedEnvFileToUpdate, updateEnvFile); + } else { + SetupCDTest.getExtendTest().log(Status.INFO, "Resource does not contain HEAT files"); + } + } + + // update all env files and verify parameters value in Deployment Artifact View + @Test + public void uploadUpdatedAllHeatEnv() throws Exception { + + String vnfFile = VFW_FNAT_30_1607_E2E_ZIP; + File updateEnvFile = null; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.getName(); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts(); + List<HeatWithParametersDefinition> envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); + if (envFilesList.size() > 0) { + for (HeatWithParametersDefinition selectedEnvFileToUpdate : envFilesList) { + // create env file and update it + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + selectedEnvFileToUpdate.getHeatEnvLabel()); + updateEnvFile = ArtifactUIUtils.uploadCreatedUpdateParametersEnvFile(selectedEnvFileToUpdate, createdEnvFilePath); + ArtifactUIUtils.verifyUpdatedEnvParameters(selectedEnvFileToUpdate, updateEnvFile); + } + } else { + SetupCDTest.getExtendTest().log(Status.INFO, "Resource does not contain HEAT files"); + } + } + + // update all env files and verify parameters value in Composition + @Test + public void uploadUpdatedAllHeatEnvComposition() throws Exception { + + String vnfFile = VLANDSLIDE_LDST_30_1607_E2E_ZIP; + File updateEnvFile = null; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.getName(); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vspName, "0.1"); + Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts(); + List<HeatWithParametersDefinition> envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.StepsEnum.COMPOSITION.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB.getValue()); + if (envFilesList.size() > 0) { + for (HeatWithParametersDefinition selectedEnvFileToUpdate : envFilesList) { + // create env file and update it + String dataTestId = DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ITEM.getValue() + selectedEnvFileToUpdate.getHeatArtifactDisplayName(); + GeneralUIUtils.hoverOnAreaByTestId(dataTestId); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + selectedEnvFileToUpdate.getHeatArtifactDisplayName()); + updateEnvFile = ArtifactUIUtils.uploadCreatedUpdateParametersEnvFile(selectedEnvFileToUpdate, createdEnvFilePath); + ArtifactUIUtils.verifyUpdatedEnvParameters(selectedEnvFileToUpdate, updateEnvFile, dataTestId); + } + } else { + SetupCDTest.getExtendTest().log(Status.INFO, "Resource does not contain HEAT files"); + } + } + + // expected heat version 1 and heatEnv 0 + @Test + // Download ENV file from VF level Update VSP. + public void downloadEnvFromVFLevelUpdateVSP() throws Throwable { + String vnfFile = VSAEGW_FDNT_30_1607_E2E_ZIP; + String updatedVnfFile = VLANDSLIDE_LDSA_30_1607_E2E_ZIP; + String downloadDirPath = SetupCDTest.getConfig().getDownloadAutomationFolder(); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject CreatedVsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + String vspName = CreatedVsp.getName(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUiUtils.updateVnfAndValidate(vnfsRepositoryPath, CreatedVsp, updatedVnfFile, getUser()); + //get updated vsp env files + Map<String, File> currentZipEnvfiles = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, downloadDirPath); + GeneralUIUtils.findComponentAndClick(vspName); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + List<String> deploymentArtifcatsList = DeploymentArtifactPage.getDeploymentArtifactsNamesWorkSpace(); + + for (int i = 0; i < deploymentArtifcatsList.size(); i++) { + if (DeploymentArtifactPage.getArtifactType(deploymentArtifcatsList.get(i)).equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + DeploymentArtifactPage.clickDownloadEnvArtifact(deploymentArtifcatsList.get(i)); + GeneralUIUtils.ultimateWait(); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(downloadDirPath); + ArtifactUIUtils.compareYamlFilesByPattern(latestFilefromDir, currentZipEnvfiles.get(deploymentArtifcatsList.get(i)), PARAMETERS); + } + } + } + + @Test + // Download ENV file from VF level Work-Space. + public void downloadEnvFromVFLevelWorkSpace() throws Exception { + String vnfFile = VSAEGW_FDNT_30_1607_E2E_ZIP; + String downloadDirPath = SetupCDTest.getConfig().getDownloadAutomationFolder(); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + Map<String, File> currentZipEnvfiles = ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.getName(), downloadDirPath); + GeneralUIUtils.findComponentAndClick(vsp.getName()); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + List<String> deploymentArtifcatsList = DeploymentArtifactPage.getDeploymentArtifactsNamesWorkSpace(); + + for (int i = 0; i < deploymentArtifcatsList.size(); i++) { + + if (DeploymentArtifactPage.getArtifactType(deploymentArtifcatsList.get(i)).equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + DeploymentArtifactPage.clickDownloadEnvArtifact(deploymentArtifcatsList.get(i)); + GeneralUIUtils.ultimateWait(); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(downloadDirPath); + ArtifactUIUtils.compareYamlFilesByPattern(latestFilefromDir, currentZipEnvfiles.get(deploymentArtifcatsList.get(i)), PARAMETERS); + } + } + } + + @Test + // Download ENV file from VF level Composition. + public void downloadEnvVFLevelComposition() throws Exception { + + String downloadDirPath = SetupCDTest.getConfig().getDownloadAutomationFolder(); + String vnfFile = VSAEGW_FDNT_30_1607_E2E_ZIP; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + Map<String, File> currentZipEnvfiles = ArtifactBusinessLogic.createEnvFilesListFromCsar(vsp.getName(), downloadDirPath); + GeneralUIUtils.findComponentAndClick(vsp.getName()); + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CompositionPage.clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB); + List<WebElement> deploymentArtifcatsList = CompositionPage.getCompositionEnvArtifacts(); + + for (int i = 0; i < deploymentArtifcatsList.size(); i++) { + String fileName = GeneralUIUtils.getDataTestIdAttributeValue(deploymentArtifcatsList.get(i)).replace(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ENV.getValue(), ""); + if (GeneralUIUtils.isElementVisibleByTestId(GeneralUIUtils.getDataTestIdAttributeValue(deploymentArtifcatsList.get(i)))) { + CompositionPage.clickDownloadEnvArtifactComposition(fileName).click(); + GeneralUIUtils.ultimateWait(); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(downloadDirPath); + ArtifactUIUtils.compareYamlFilesByPattern(latestFilefromDir, currentZipEnvfiles.get(fileName), PARAMETERS); + } + } + } + + @Test + // Download ENV file from VF level Update parameters in UI. + public void downloadEnvVFLevelUpdateParameters() throws Exception { + + String vnfFile = VFW_FCGI_30_1607_E2E_ZIP; + String downloadDirPath = SetupCDTest.getConfig().getDownloadAutomationFolder(); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vendorSoftwareProductObject = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + Resource resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vendorSoftwareProductObject.getName(), "0.1"); + Map<String, ArtifactDefinition> deploymentArtifacts = resource.getDeploymentArtifacts(); + List<HeatWithParametersDefinition> envFilesList = ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts); + + for (int i = 0; i < envFilesList.size(); i++) { + String artifactName = envFilesList.get(i).getHeatArtifactDisplayName(); + if (envFilesList.get(i).getHeatArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType())) { + ExtentTestActions.log(Status.INFO, String.format("Opening the edit/view artifact parameters form of %s resource...", vnfFile)); + DeploymentArtifactPage.clickEditEnvArtifact(envFilesList.get(i).getHeatArtifactDisplayName()); + + ExtentTestActions.log(Status.INFO, String.format("Going To locating all artifact parameters from UI of %s artifact...", artifactName)); + Map<?, ?> dataToWriteInUI = ArtifactUIUtils.getDataToWriteInUI(envFilesList.get(i).getHeatParameterDefinition()); + Map<?, ?> data = dataToWriteInUI; + ExtentTestActions.log(Status.INFO, String.format("Success to locate all artifact parameters from UI of %s artifact...", artifactName)); + + List<HeatParameterDataDefinition> listToSearchEnvParametersInUI = envFilesList.get(i).getHeatParameterDefinition(); + fillHeatEnvParametersInUi(data, listToSearchEnvParametersInUI); + + DeploymentArtifactPage.clickSaveEnvParameters(); + GeneralUIUtils.waitForLoader(); + ExtentTestActions.log(Status.INFO, String.format("Going to get the %s updated resource ...", vendorSoftwareProductObject.getName())); + resource = AtomicOperationUtils.getResourceObjectByNameAndVersion(UserRoleEnum.DESIGNER, vendorSoftwareProductObject.getName(), "0.1"); + deploymentArtifacts = resource.getDeploymentArtifacts(); + Map<String, List<HeatWithParametersDefinition>> envFilesListupdated = new HashMap<>(); + ExtentTestActions.log(Status.INFO, String.format("Mapping the %s artifact parameters ...", artifactName)); + envFilesListupdated.put(artifactName, ArtifactBusinessLogic.extractHeatWithParametersDefinition(deploymentArtifacts)); + List<HeatWithParametersDefinition> heatEnvUpdatedParameters = envFilesListupdated.get(artifactName); + DeploymentArtifactPage.clickDownloadEnvArtifact(artifactName); + + Map<String, Object> mapExpectedProperties = new HashMap<>(); + for (HeatParameterDataDefinition param : heatEnvUpdatedParameters.get(i).getHeatParameterDefinition()) { + mapExpectedProperties.put(param.getName(), ArtifactUIUtils.getValue(param)); + } + ArtifactUIUtils.compareYamlParametersByPattern(mapExpectedProperties, FileHandling.getLastModifiedFileNameFromDir(downloadDirPath), PARAMETERS); + } + } + } + + + @Test + public void checkDefaultCreatedEnvArtifacts() throws Exception { + String vnfFile = VIXIA_IXLA_30_1607_E2E_ZIP; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.getName(); + Map<String, File> generatedEnvFileList = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, filePath); + HomeUtils.findComponentAndClick(vspName); + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.DEPLOYMENT_ARTIFACT); + for (Entry<String, File> envFileEntry : generatedEnvFileList.entrySet()) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + envFileEntry.getKey()); + ArtifactUIUtils.compareYamlFilesByPattern(envFileEntry.getValue(), FileHandling.getLastModifiedFileNameFromDir(), PARAMETERS); +// if(true){ +//// throw new SkipException("Test skipped, new artifact version design should be developed"); +// SetupCDTest.getExtendTest().log(Status.INFO, "Test skipped, new artifact version design should be developed"); +// } +// ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "1", ArtifactTypeEnum.HEAT_ENV); +// ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "1", ArtifactTypeEnum.HEAT); + } + } + + // ------------------------------------------------------------------------------- + @Test(dataProvider = "heatEnvAndVersion") + public void checkDefaultCreatedEnvArtifactsAfterVspUpdate(String vnfFile, String updatedVnfFile, String expectedHeatVersion, String expectedHeatEnvVersion) throws Throwable { + String stringForLog = String.format("%s:%s:%s:%s", vnfFile, updatedVnfFile, expectedHeatVersion, expectedHeatEnvVersion); + setLog(stringForLog); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.getName(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUiUtils.updateVnfAndValidate(vnfsRepositoryPath, vsp, updatedVnfFile, getUser()); + Map<String, File> generatedUpdatedEnvFileList = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, filePath); + HomeUtils.findComponentAndClick(vspName); + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.DEPLOYMENT_ARTIFACT); + for (Entry<String, File> envFileEntry : generatedUpdatedEnvFileList.entrySet()) { +// TODO test will pass on case all objects on deployment view are visible + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + envFileEntry.getKey()); + ArtifactUIUtils.compareYamlFilesByPattern(envFileEntry.getValue(), FileHandling.getLastModifiedFileNameFromDir(), PARAMETERS); +// ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), expectedHeatEnvVersion, ArtifactTypeEnum.HEAT_ENV); +// ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), expectedHeatVersion, ArtifactTypeEnum.HEAT); + } + if (true) { +// throw new SkipException("Test skipped, new artifact version design should be developed"); + ExtentTestActions.log(Status.INFO, "Test skipped, new artifact version design should be developed"); + } + } + + // expected heat version 1 and heatEnv 3 + @Test + public void checkDefaultCreatedEnvArtifactsVspUpdatedWithSameVspTwice() throws Throwable { + String vnfFile = VFW_FCGI_30_1607_E2E_ZIP; + String updatedVnfFile = VFW_FCGI_30_1607_E2E_ZIP; + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); //getResourceReqDetails(ComponentConfigurationTypeEnum.DEFAULT); + VendorSoftwareProductObject vsp = OnboardingUiUtils.onboardAndValidate(resourceReqDetails, vnfsRepositoryPath, vnfFile, getUser()); + String vspName = vsp.getName(); + + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUiUtils.updateVnfAndValidate(vnfsRepositoryPath, vsp, updatedVnfFile, getUser()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + OnboardingUiUtils.updateVnfAndValidate(vnfsRepositoryPath, vsp, updatedVnfFile, getUser()); + // Artifact validation commented until new artifact version design should be developed + Map<String, File> generatedUpdatedSecondTimeEnvFileList = ArtifactBusinessLogic.createEnvFilesListFromCsar(vspName, filePath); + HomeUtils.findComponentAndClick(vspName); + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.DEPLOYMENT_ARTIFACT); + for (Entry<String, File> envFileEntry : generatedUpdatedSecondTimeEnvFileList.entrySet()) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + envFileEntry.getKey()); + ArtifactUIUtils.compareYamlFilesByPattern(envFileEntry.getValue(), FileHandling.getLastModifiedFileNameFromDir(), PARAMETERS); + if (true) { +// throw new SkipException("Test skipped, new artifact version design should be developed"); + ExtentTestActions.log(Status.INFO, "Test skipped, new artifact version design should be developed"); + } +// ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "3", ArtifactTypeEnum.HEAT_ENV); +// ArtifactUIUtils.validateArtifactVersionByTypeAndLabel(envFileEntry.getKey(), "1", ArtifactTypeEnum.HEAT); + } + } + + + public void downloadFile(Entry<String, File> envFileEntry) { + int fileCountBefore = FileHandling.getFileCountFromDefaulDownloadDirectory(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + envFileEntry.getKey()); + int fileCountAfter = FileHandling.getFileCountFromDefaulDownloadDirectory(); + assertTrue("Downloaded file is missing", (fileCountAfter - fileCountBefore) == 1); + } + + public static void fillHeatEnvParametersInUi(Map<?, ?> data, List<HeatParameterDataDefinition> listToSearchEnvParametersInUI) { + ExtentTestActions.log(Status.INFO, String.format("Going to search parameters in UI and insert new current value to each parameter in UI...")); + + for (HeatParameterDataDefinition paramDefinition : listToSearchEnvParametersInUI) { + DeploymentArtifactPage.searchBoxEnv(paramDefinition.getName()); + WebElement currenValueField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.EnvParameterView.ENV_CURRENT_VALUE.getValue() + paramDefinition.getName()); + currenValueField.clear(); + currenValueField.sendKeys(data.get(paramDefinition.getName()).toString()); + GeneralUIUtils.ultimateWait(); + DeploymentArtifactPage.clearSearchBoxEnv(); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java new file mode 100644 index 0000000000..59956daf91 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/sanity/VfDeploymentInformationalArtifacts.java @@ -0,0 +1,640 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.sanity; + +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.utilities.ArtifactUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.openecomp.sdc.common.api.ArtifactTypeEnum; +import org.openqa.selenium.WebElement; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + + +public class VfDeploymentInformationalArtifacts extends SetupCDTest { + + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // START US824719 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // US824719 - Import VSP - VF informational artifacts + // TC1434241 - Import VF Artifacts - Deployment Artifacts - One Artifact, One Type + @Test + public void importVfArtifactsDeploymentArtifactsOneArtifactOneType() throws Exception { + String fileName = "TC1434241.csar"; + String folder = "US825779"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434245 - Import VF Artifacts - Deployment Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfArtifactsDeploymentArtifactsMultipleArtifactsMultipleTypes() throws Exception { + String fileName = "TC1434245.csar"; + String folder = "US825779"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1")); + + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434247 - Import VF Artifacts - Informational Artifacts - One Artifact, One Type + @Test + public void importVfArtifactsInformationalArtifactsOneArtifactOneType() throws Exception { + String fileName = "TC1434247.csar"; + String folder = "US825779"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434248 - Import VF Artifacts - Informational Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfArtifactsInformationalArtifactsMultipleArtifactsMultipleTypes() throws Exception { + String fileName = "TC1434248.csar"; + String folder = "US825779"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1434249 - Import VF Artifacts - Deployment and Informational Artifacts - Multiple Artifacts, Multiple Types + @Test + public void importVfArtifactsDeploymentAndInformationalArtifactsMultipleArtifactsMultipleTypes() throws Exception { + String fileName = "TC1434249.csar"; + String folder = "US825779"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "HeatVolArtifactName3.yaml", null, "HeatVolArtifactName3", ArtifactTypeEnum.HEAT_VOL.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // TODO: there is defect in flow: "Updated button enabled for artifact in invalid type folder" + // TODO: re-check it after defect fix + // US824719 - Import VSP - VF informational artifacts + // TC1438310 - Import VF Artifacts - Deployment Artifacts - Artifact Type Invalid + @Test + public void importVFArtifactsDeploymentArtifactsArtifactTypeInvalid() throws Exception { + String fileName = "DeploymentArtifactWithInvalidType.csar"; + String folder = "US825779"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1438311 - Import VF Artifacts - Informational Artifacts - Artifact Type Invalid + @Test + public void importVfArtifactsInformationalArtifactsArtifactTypeInvalid() throws Exception { + String fileName = "InformationArtifactWithInvalidType.csar"; + String folder = "US825779"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>(); + informationalArtifacts.add(new ArtifactInfo(null, "ArtifactName.yaml", null, "ArtifactName", ArtifactTypeEnum.OTHER.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1438231 - Import VF Artifacts - Deployment Artifacts - Artifact Name To Long + @Test + public void importVfArtifactsDeploymentArtifactsArtifactNameToLong() throws Exception { + String folder = "US825779"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String fileName = "DeploymentArtifactWithLongName.csar"; + + importVfFromCsar(resourceMetaData, folder, fileName, getUser()); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + assertThat(errorMessage).contains(checkUIResponseOnError); + } + + // US824719 - Import VSP - VF informational artifacts + // TC1438232 - Import VF Artifacts - Informational Artifacts - Artifact Name To Long + // TODO: make informational artifact name longer then 255 + // TODO: windows/linux not allowed it + @Test(enabled = true) + public void importVfArtifactsInformationalArtifactsArtifactNameToLong() throws Exception { + String folder = "US825779"; + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + + String fileName = "InformationArtifactWithLongName.csar"; + + importVfFromCsar(resourceMetaData, folder, fileName, getUser()); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + assertThat(errorMessage).contains(checkUIResponseOnError); + } + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // END US824719 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // START US825779 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1443954 - Update With Multiple Changes In Deployment And Informational Artifacts + @Test + public void updateWithMultipleChangesInDeploymentAndInformationalArtifacts() throws Exception { + String folder = "US825779"; + String fileName = "ImportTC1443954.csar"; + + ArtifactInfo deploymentHeat1 = new ArtifactInfo(null, "heatartifactname1.yaml", null, "heatartifactname1", ArtifactTypeEnum.HEAT.getType(), "1"); + ArtifactInfo deploymentHeat2 = new ArtifactInfo(null, "heatartifactname2.yaml", null, "heatartifactname2", ArtifactTypeEnum.HEAT.getType(), "1"); + ArtifactInfo deploymentHeat3 = new ArtifactInfo(null, "heatartifactname3.yaml", null, "heatartifactname3", ArtifactTypeEnum.HEAT.getType(), "1"); + + ArtifactInfo deploymentHeatVol1 = new ArtifactInfo(null, "HeatVolArtifactName1.yaml", null, "HeatVolArtifactName1", ArtifactTypeEnum.HEAT_VOL.getType(), "1"); + ArtifactInfo deploymentHeatVol2 = new ArtifactInfo(null, "HeatVolArtifactName2.yaml", null, "HeatVolArtifactName2", ArtifactTypeEnum.HEAT_VOL.getType(), "1"); + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(deploymentHeat1); + deploymentArtifacts.add(deploymentHeat2); + deploymentArtifacts.add(deploymentHeat3); + deploymentArtifacts.add(deploymentHeatVol1); + deploymentArtifacts.add(deploymentHeatVol2); + + ArtifactInfo infoGuide1 = new ArtifactInfo(null, "GuideInfoArtifact1.yml", null, "GuideInfoArtifact1", ArtifactTypeEnum.GUIDE.getType(), "1"); + ArtifactInfo infoGuide2 = new ArtifactInfo(null, "GuideInfoArtifact2.yml", null, "GuideInfoArtifact2", ArtifactTypeEnum.GUIDE.getType(), "1"); + + ArtifactInfo infoOther1 = new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1"); + ArtifactInfo infoOther2 = new ArtifactInfo(null, "artifactname2.txt", null, "artifactname2", ArtifactTypeEnum.OTHER.getType(), "1"); + ArtifactInfo infoOther3 = new ArtifactInfo(null, "artifactname3.txt", null, "artifactname3", ArtifactTypeEnum.OTHER.getType(), "1"); + + List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>(); + informationalArtifacts.add(infoGuide1); + informationalArtifacts.add(infoGuide2); + informationalArtifacts.add(infoOther1); + informationalArtifacts.add(infoOther2); + informationalArtifacts.add(infoOther3); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1443954.csar"; + + List<ArtifactInfo> informationalArtifactsNotExist = new ArrayList<ArtifactInfo>(); + List<ArtifactInfo> deploymentArtifactsNotExist = new ArrayList<ArtifactInfo>(); + + // Changes in deployment artifacts + deploymentArtifactsNotExist.add(deploymentHeat1); + deploymentArtifactsNotExist.add(deploymentHeat2); + deploymentArtifacts.remove(deploymentHeat1); + deploymentArtifacts.remove(deploymentHeat2); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname4.yaml", null, "heatartifactname4", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "heatartifactname5.yaml", null, "heatartifactname5", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentHeatVol1.setArtifactVersion("2"); + deploymentHeatVol2.setArtifactVersion("2"); + + // Changes in informational artifacts + infoGuide1.setArtifactVersion("2"); + infoOther1.setArtifactVersion("2"); + informationalArtifactsNotExist.add(infoGuide2); + informationalArtifactsNotExist.add(infoOther2); + informationalArtifacts.remove(infoGuide2); + informationalArtifacts.remove(infoOther2); + informationalArtifacts.add(new ArtifactInfo(null, "GuideInfoArtifact3.yml", null, "GuideInfoArtifact3", ArtifactTypeEnum.GUIDE.getType(), "1")); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname4.txt", null, "artifactname4", ArtifactTypeEnum.OTHER.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, deploymentArtifacts, informationalArtifacts, deploymentArtifactsNotExist, informationalArtifactsNotExist); + } + + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444206 - Update With Existed Deployment Artifact By Artifact With Different Type + @Test + public void updateWithExistedDeploymentArtifactByArtifactWithDifferentType() throws Exception { + String folder = "US825779"; + String fileName = "ImportTC1444206.csar"; + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444206.csar"; + String filePath = FileHandling.getFilePath(folder); + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.ARTIFACT_EXIST.name()); + assertThat(errorMessage).contains(checkUIResponseOnError); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444207 - Update With Existed Informational Artifact By Artifact With Different Type + @Test + public void updateWithExistedInformationalArtifactByArtifactWithDifferentType() throws Exception { + String folder = "US825779"; + String fileName = "ImportTC1444207.csar"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, informationalArtifacts); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444207.csar"; + String filePath = FileHandling.getFilePath(folder); + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.ARTIFACT_EXIST.name()); + assertThat(errorMessage).contains(checkUIResponseOnError); + } + + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444208 - Update With Existed Informational Artifact By Deployment Artifact With Different Type + @Test + public void updateWithExistedInformationalArtifactByDeploymentArtifactWithDifferentType() throws Exception { + String folder = "US825779"; + String fileName = "ImportTC1444208.csar"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + deploymentArtifacts.add(new ArtifactInfo(null, "artifactname1.yaml", null, "artifactname1", ArtifactTypeEnum.HEAT.getType(), "1")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444208.csar"; + String filePath = FileHandling.getFilePath(folder); + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.ARTIFACT_EXIST.name()); + assertThat(errorMessage).contains(checkUIResponseOnError); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444520 - Update Deployment Artifact With Name To Long + @Test + public void updateDeploymentArtifactWithNameToLong() throws Exception { + String folder = "US825779"; + + String fileName = "ImportTC1444520.csar"; + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, null, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444520.csar"; + String filePath = FileHandling.getFilePath(folder); + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + assertThat(errorMessage).contains(checkUIResponseOnError); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444521 - Update Informational Artifact With Name To Long + @Test + public void updateInformationalArtifactWithNameToLong() throws Exception { + + String folder = "US825779"; + String fileName = "ImportTC1444521.csar"; + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, null, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444521.csar"; + String filePath = FileHandling.getFilePath(folder); + + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + String errorMessage = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + String checkUIResponseOnError = ErrorValidationUtils.checkUIResponseOnError(ActionStatus.EXCEEDS_LIMIT.name()); + assertThat(errorMessage).contains(checkUIResponseOnError); + } + + // US825779 - Story: [BE] Import VSP - VF informational artifacts - Update + // TC1444531 - Update Informational Artifact With Invalid Type + @Test + public void updateInformationalArtifactWithInvalidType() throws Exception { + String folder = "US825779"; + String fileName = "ImportTC1444531.csar"; + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, null, null); + + GeneralUIUtils.clickOnElementByTestId("breadcrumbs-button-1"); + + fileName = "UpdateTC1444531.csar"; + + List<ArtifactInfo> informationalArtifacts = new ArrayList<ArtifactInfo>(); + informationalArtifacts.add(new ArtifactInfo(null, "artifactname1.xml", null, "artifactname1", ArtifactTypeEnum.OTHER.getType(), "1")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, fileName, null, informationalArtifacts, null, null); + } + + + @Test + public void importValidInformationalArtifactInInvalidFolerTest_TC1438313() throws Exception { + String fileName = "ValidArtifactNameInInvalidFolder.csar"; + String folder = "US824719"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "1")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + + importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(fileName, folder, deploymentArtifacts, null); + } + + @Test + public void updateValidInformationalArtifactInInvalidFolerTest_TC1444533() throws Exception { + String fileName = "ImportTC1444533.csar"; + String folder = "US824719"; + String filePath = FileHandling.getFilePath(folder); + + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + + String updatedCsarFileName = "UpdateTC1444533.csar"; + + List<ArtifactInfo> deploymentArtifacts = new ArrayList<ArtifactInfo>(); + deploymentArtifacts.add(new ArtifactInfo(null, "base_ldsa.yaml", null, "base_ldsa", ArtifactTypeEnum.HEAT.getType(), "2")); + deploymentArtifacts.add(new ArtifactInfo(null, "module_1_ldsa.yaml", null, "module_1_ldsa", ArtifactTypeEnum.HEAT.getType(), "4")); + + updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(folder, updatedCsarFileName, deploymentArtifacts, null, null, null); + } + + + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // END US825779 + ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + + + public void updateVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(String folder, String fileName, + List<ArtifactInfo> deploymentArtifacts, List<ArtifactInfo> informationalArtifacts, + List<ArtifactInfo> deploymentArtifactsNotExist, List<ArtifactInfo> informationalArtifactsNotExist) throws Exception { + String filePath = FileHandling.getFilePath(folder); + ResourceUIUtils.updateVfWithCsar(filePath, fileName); + + validateDeploymentArtifactPage(deploymentArtifacts, null); + validateInformationalArtifactPage(informationalArtifacts, null); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + validateDeploymentArtifactInComposition(deploymentArtifacts, null); + validateInformationalArtifactInComposition(informationalArtifacts, null); + + } + + + public void importVfFromCsar(ResourceReqDetails resourceMetaData, String folder, String fileName, User user) { + String filePath = FileHandling.getFilePath(folder); + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.IMPORT_AREA.getValue()); + // Insert file to the browse dialog + WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + browseWebElement.sendKeys(filePath + fileName); + + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + ResourceUIUtils.fillResourceGeneralInformationPage(resourceMetaData, getUser(), true); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + } + + + public void importVfAndValidateInformationalDeploymentArtifactPagesOnPagesAndComposition(String fileName, String folder, List<ArtifactInfo> deploymentArtifacts, List<ArtifactInfo> informationalArtifacts) throws Exception { + String filePath = FileHandling.getFilePath(folder); + ResourceReqDetails resourceMetaData = ElementFactory.getDefaultResourceByType(ResourceTypeEnum.VF, getUser()); + ResourceUIUtils.importVfFromCsar(resourceMetaData, filePath, fileName, getUser()); + + validateDeploymentArtifactPage(deploymentArtifacts, null); + validateInformationalArtifactPage(informationalArtifacts, null); + + ResourceGeneralPage.getLeftMenu().moveToCompositionScreen(); + + validateDeploymentArtifactInComposition(deploymentArtifacts, null); + validateInformationalArtifactInComposition(informationalArtifacts, null); + } + + public void validateInformationalArtifactInComposition(List<ArtifactInfo> informationalArtifacts, List<ArtifactInfo> informationalArtifactsNotExist) throws Exception { + CompositionPage.showInformationArtifactTab(); + // Composition informational + if (informationalArtifacts != null && informationalArtifacts.size() > 0) { + validateEachArtifactOnCompositionRightMenuInformationPage(informationalArtifacts); + } + if (informationalArtifactsNotExist != null && informationalArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistOnCompositionRightMenuInformationPage(informationalArtifactsNotExist); + } + } + + public void validateDeploymentArtifactInComposition(List<ArtifactInfo> deploymentArtifacts, List<ArtifactInfo> deploymentArtifactsNotExist) throws Exception { + CompositionPage.showDeploymentArtifactTab(); + // Composition deployment + if (deploymentArtifacts != null && deploymentArtifacts.size() > 0) { + validateEachArtifactOnCompositionRightMenuDeploymentPage(deploymentArtifacts); + } + if (deploymentArtifactsNotExist != null && deploymentArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistOnCompositionRightMenuDeploymentPage(deploymentArtifactsNotExist); + } + } + + public void validateInformationalArtifactPage(List<ArtifactInfo> informationalArtifacts, List<ArtifactInfo> informationalArtifactsNotExist) { + ResourceGeneralPage.getLeftMenu().moveToInformationalArtifactScreen(); + // Informational page + if (informationalArtifacts != null && informationalArtifacts.size() > 0) { + validateEachArtifactInformationPage(informationalArtifacts); + } + if (informationalArtifactsNotExist != null && informationalArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistInformationPage(informationalArtifactsNotExist); + } + } + + public void validateDeploymentArtifactPage(List<ArtifactInfo> deploymentArtifacts, List<ArtifactInfo> deploymentArtifactsNotExist) { + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + // Deployment page + if (deploymentArtifacts != null && deploymentArtifacts.size() > 0) { + validateEachArtifactOnDeploymentPage(deploymentArtifacts); + } + if (deploymentArtifactsNotExist != null && deploymentArtifactsNotExist.size() > 0) { + validateEachArtifactNotExistOnDeploymentPage(deploymentArtifactsNotExist); + } + } + + // TODO: add validation that if not editable / deleteable then button should not appear + public void validateEachArtifactOnDeploymentPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + String type = artifact.getArtifactType(); + String label = artifact.getArtifactLabel(); + String version = artifact.getArtifactVersion(); + + if (type.equals(ArtifactTypeEnum.HEAT.getType()) || type.equals(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equals(ArtifactTypeEnum.HEAT_NET.getType())) { + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(label, null, version, type, true, false, false, true); + } else { + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(label, null, version, type, true, true, true, false); + } + } + } + + public void validateEachArtifactNotExistOnDeploymentPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + public void validateEachArtifactInformationPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + ArtifactUIUtils.validateExistArtifactOnDeploymentInformationPage(artifact.getArtifactLabel(), null, artifact.getArtifactVersion(), artifact.getArtifactType(), true, true, true, false); + } + } + + public void validateEachArtifactNotExistInformationPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + public void validateEachArtifactOnCompositionRightMenuDeploymentPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + + String type = artifact.getArtifactType(); + String label = artifact.getArtifactLabel(); + String filename = artifact.getFilename(); + + if (type.equals(ArtifactTypeEnum.HEAT.getType()) || type.equals(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equals(ArtifactTypeEnum.HEAT_NET.getType())) { + ArtifactUIUtils.validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(filename, label, false, true, true, false); + } else { + ArtifactUIUtils.validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(filename, label, true, false, true, true); + } + } + } + + public void validateEachArtifactNotExistOnCompositionRightMenuDeploymentPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnCompositionRightMenuDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + // TODO: there is defect in this flow + // TODO: change isEditable to false when defect fix + public void validateEachArtifactOnCompositionRightMenuInformationPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + ArtifactUIUtils.validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(artifact.getFilename(), artifact.getArtifactLabel(), true, false, true, true); + } + } + + public void validateEachArtifactNotExistOnCompositionRightMenuInformationPage(List<ArtifactInfo> artifactInfoList) { + for (ArtifactInfo artifact : artifactInfoList) { + ArtifactUIUtils.validateNotExistArtifactOnCompositionRightMenuDeploymentInformationPage(artifact.getArtifactLabel()); + } + } + + + @Override + protected UserRoleEnum getRole() { + return UserRoleEnum.DESIGNER; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ArtifactsCorrelationManager.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ArtifactsCorrelationManager.java new file mode 100644 index 0000000000..fa8b8a171e --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ArtifactsCorrelationManager.java @@ -0,0 +1,72 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map.Entry; +import java.util.Set; + +public class ArtifactsCorrelationManager { + + private static HashMap<String, LinkedList<HeatMetaFirstLevelDefinition>> vNFArtifactsCorrelationMap = new HashMap<String, LinkedList<HeatMetaFirstLevelDefinition>>(); + private static HashMap<String, Entry<String, LinkedList<HeatMetaFirstLevelDefinition>>> serviceVNFCorrelationMap = new HashMap<String, Entry<String, LinkedList<HeatMetaFirstLevelDefinition>>>(); + + public static void addVNFartifactDetails(String vspName, + LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts) { + + vNFArtifactsCorrelationMap.put(vspName, deploymentArtifacts); + + + } + + public static Entry<String, LinkedList<HeatMetaFirstLevelDefinition>> getVNFartifactDetails(String vnfName) { + + + Set<Entry<String, LinkedList<HeatMetaFirstLevelDefinition>>> entrySet = vNFArtifactsCorrelationMap.entrySet(); + for (Entry<String, LinkedList<HeatMetaFirstLevelDefinition>> entry : entrySet) { + String key = entry.getKey(); + if (key.equals(vnfName)) { + return entry; + } + + } + return null; + + } + + + public static void addVNFtoServiceArtifactCorrelation(String service, String vnfName) { + + serviceVNFCorrelationMap.put(service, getVNFartifactDetails(vnfName)); + + } + + public static Set<Entry<String, Entry<String, LinkedList<HeatMetaFirstLevelDefinition>>>> getServiceArtifactCorrelationMap(String service) { + + return serviceVNFCorrelationMap.entrySet(); + + } + +} + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/AttFtpClient.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/AttFtpClient.java new file mode 100644 index 0000000000..aa6328d318 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/AttFtpClient.java @@ -0,0 +1,211 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import org.apache.commons.net.ftp.FTPClient; +import org.apache.commons.net.ftp.FTPFile; +import org.apache.commons.net.ftp.FTPReply; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +public class AttFtpClient { + + private static final AttFtpClient FTP_CLIENT = new AttFtpClient(); + + public static AttFtpClient getFtpClient() { + return FTP_CLIENT; + } + + private FTPClient apacheFtpClient; + + private AttFtpClient() { + apacheFtpClient = new FTPClient(); + } + + + public void init(String server, int port, String user, String pass) { + + try { + apacheFtpClient.connect(server, port); + showServerReply(apacheFtpClient); + + + int replyCode = apacheFtpClient.getReplyCode(); + if (!FTPReply.isPositiveCompletion(replyCode)) { + System.out.println("Connect failed"); + return; + } + + boolean success = apacheFtpClient.login(user, pass); + showServerReply(apacheFtpClient); + + if (!success) { + System.out.println("Could not login to the server"); + return; + } + } catch (IOException ex) { + System.out.println("Oops! Something wrong happened"); + ex.printStackTrace(); + } + } + + public File retrieveLastModifiedFileFromFTP() throws IOException { + FTPFile[] files1 = retrieveListOfFile(); + + // sort list by TimeStamp + List<FTPFile> sorted = Arrays.asList(files1).stream() + .sorted(Comparator.comparing(FTPFile::getTimestamp)).collect(Collectors.toList()); + printFileDetailsList(sorted); + + // retrieve file from FTP + FTPFile ftpFile = sorted.get(sorted.size() - 1); + + return retrieveFileFromFTP(ftpFile); + + } + + public FTPFile[] retrieveListOfFile() throws IOException { + // Lists files and directories + FTPFile[] files = apacheFtpClient.listFiles(""); + + printNames(files); + return files; + } + + public File retrieveFileFromFTP(FTPFile ftpFile) throws IOException { + + File downloadFile1 = new File("tmp"); + OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1)); + boolean success = apacheFtpClient.retrieveFile(ftpFile.getName(), outputStream1); + outputStream1.close(); + + if (success) { + System.out.println("File #1 has been downloaded successfully."); + } + + + return downloadFile1; + + } + + public void deleteFilesFromFTPserver() throws IOException { + FTPFile[] files = retrieveListOfFile(); + deleteFiles(files); + } + + public void terminateClient() throws IOException { + + String status = apacheFtpClient.getStatus(); + + // logs out and disconnects from server + try { + if (apacheFtpClient.isConnected()) { + apacheFtpClient.logout(); + apacheFtpClient.disconnect(); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + private void printFileDetailsList(List<FTPFile> list) { + DateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + + for (FTPFile ftpFile : list) { + + String details = ftpFile.getName(); + if (ftpFile.isDirectory()) { + details = "[" + details + "]"; + } + details += "\t\t" + ftpFile.getSize(); + details += "\t\t" + dateFormater.format(ftpFile.getTimestamp().getTime()); + + System.out.println(details); + } + } + + private void printNames(FTPFile[] files) { + if (files != null && files.length > 0) { + for (FTPFile aFile : files) { + System.out.println(aFile); + } + } + } + + private void showServerReply(FTPClient ftpClient) { + String[] replies = ftpClient.getReplyStrings(); + if (replies != null && replies.length > 0) { + for (String aReply : replies) { + System.out.println("SERVER: " + aReply); + } + } + } + + public class LastModifiedComparator implements Comparator<FTPFile> { + + public int compare(FTPFile f1, FTPFile f2) { + return f1.getTimestamp().compareTo(f2.getTimestamp()); + } + } + + public FTPFile getMaxLastModified(FTPFile[] ftpFiles) { + return Collections.max(Arrays.asList(ftpFiles), new LastModifiedComparator()); + } + + public static void displayFiles(File[] files) { + for (File file : files) { + System.out.printf("File: %-20s Last Modified:" + new Date(file.lastModified()) + "\n", file.getName()); + } + } + + public void deleteFiles(FTPFile[] files) { + + for (FTPFile file : files) { + + boolean deleted = false; + try { + deleted = apacheFtpClient.deleteFile(file.getName()); + } catch (IOException e) { + e.printStackTrace(); + } + + if (deleted) { + System.out.println("The file was deleted successfully."); + } else { + System.out.println("Could not delete the file, it may not exist."); + } + } + + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/DriverFactory.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/DriverFactory.java new file mode 100644 index 0000000000..78f3316635 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/DriverFactory.java @@ -0,0 +1,125 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + + +import org.apache.commons.io.FileUtils; +import org.onap.sdc.backend.ci.tests.config.Config; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; + + +public class DriverFactory { + + private static ThreadLocal<WebDriverThread> driverThread; + private static List<WebDriverThread> webDriverThreadPool = Collections.synchronizedList(new ArrayList<WebDriverThread>()); + private static Config config; + + public DriverFactory() { + try { + config = Utils.getConfig(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + @BeforeSuite(alwaysRun = true) + public static void instantiateDriverObject() { + + File basePath = new File(FileHandling.getBasePath()); + File[] listFiles = basePath.listFiles(new FilenameFilter() { + + @Override + public boolean accept(File basePath, String name) { + return name.startsWith(config.getDownloadAutomationFolder()); + } + }); + Arrays.asList(listFiles).forEach(e -> FileHandling.deleteDirectory(e.getAbsolutePath())); + + + driverThread = new ThreadLocal<WebDriverThread>() { + @Override + protected WebDriverThread initialValue() { + WebDriverThread webDriverThread = new WebDriverThread(config); + webDriverThreadPool.add(webDriverThread); + return webDriverThread; + } + }; + } + + public static WebDriver getDriver() { + return driverThread.get().getDriver(); + } + + public static FirefoxProfile getDriverFirefoxProfile() throws Exception { + return driverThread.get().getFirefoxProfile(); + } + + @AfterSuite(alwaysRun = true) + public static void quitDriverAfterSuite() throws Exception { + for (WebDriverThread webDriverThread : webDriverThreadPool) { + if (webDriverThread.getDriver() != null) { + webDriverThread.quitDriver(); + } + } + MobProxy.removeAllProxyServers(); + cleanDownloadDirs(); + } + + private static void cleanDownloadDirs() throws IOException { + HashMap<Long, WindowTest> windowMap = WindowTestManager.getWholeMap(); + for (WindowTest win : windowMap.values()) { + String downloadDirectory = win.getDownloadDirectory(); + FileUtils.cleanDirectory(new File(downloadDirectory)); + } + } + + public static void quitDriver() throws Exception { + driverThread.get().quitDriver(); + driverThread.remove(); + WindowTestManager.removeWindowTest(); + MobProxy.removePoxyServer(); + } + + public static Config getConfig() { + return config; + } + + public static void setConfig(Config config) { + DriverFactory.config = config; + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentManager.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentManager.java new file mode 100644 index 0000000000..338a9e62c6 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentManager.java @@ -0,0 +1,166 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +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.onap.sdc.backend.ci.tests.config.Config; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.onap.sdc.backend.ci.tests.utils.rest.AutomationUtils; +import org.testng.ITestContext; + +import java.io.File; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.GregorianCalendar; + +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; + + public enum suiteNameXml { + + TESTNG_FAILED_XML_NAME("testng-failed.xml"); + + suiteNameXml(String value) { + this.value = value; + } + + private String value; + + public String getValue() { + return value; + } + + } + + private static synchronized ExtentReports setReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception { + String dbIp = DriverFactory.getConfig().getReportDBhost(); + int dbPort = DriverFactory.getConfig().getReportDBport(); + + 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; + } + + private static synchronized void setExtentXReporter(Boolean isAppend) { + extentxReporter.setAppendExisting(isAppend); + extent.attachReporter(extentxReporter); + } + + private static synchronized void initAndSetExtentHtmlReporter(String filePath, String htmlFile, Boolean isAppend) throws Exception { + htmlReporter = new ExtentHtmlReporter(filePath + htmlFile); + setConfiguration(htmlReporter); + htmlReporter.setAppendExisting(isAppend); + extent.attachReporter(htmlReporter); + } + + static synchronized ExtentReports getReporter() { + return extent; + } + + 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); + String reportStartDate = null; + 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(SetupCDTest.getReportFolder()); + FileHandling.createDirectory(filepath); + setReporter(filepath, htmlFile, false); + Calendar calendar = new GregorianCalendar(); + SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a"); + reportStartDate = formatter.format(calendar.getTime()); + reporterDataDefinition(onboardVersion, osVersion, envData, suiteName); + AutomationUtils.createVersionsInfoFile(filepath + VERSIONS_INFO_FILE_NAME, onboardVersion, osVersion, envData, suiteName, reportStartDate); + } + + } + + private 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); + } + + 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; + } + + private static synchronized ExtentHtmlReporter setConfiguration(ExtentHtmlReporter htmlReporter) throws Exception { + + htmlReporter.config().setTheme(Theme.STANDARD); + htmlReporter.config().setEncoding("UTF-8"); + htmlReporter.config().setProtocol(Protocol.HTTPS); + htmlReporter.config().setDocumentTitle("SDC Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(true); + htmlReporter.config().setReportName("SDC Automation Report"); + htmlReporter.config().setChartVisibilityOnOpen(false); + htmlReporter.setStartTime(null); + return htmlReporter; + } + + public static void closeReporter() { + extent.flush(); + } + + private static void setTrafficCaptue(Config config) { + boolean mobProxyStatus = config.getUseBrowserMobProxy(); + if (mobProxyStatus) { + config.setCaptureTraffic(true); + } + } +} + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentTestActions.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentTestActions.java new file mode 100644 index 0000000000..72b2d14335 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentTestActions.java @@ -0,0 +1,127 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +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 org.onap.sdc.backend.ci.tests.api.SomeInterface; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.util.Optional; +import java.util.UUID; + +public final class ExtentTestActions { + + private static final SomeInterface testManager = ExtentTestManager.getInstance(); + private static final Logger LOGGER = LoggerFactory.getLogger(ExtentTestActions.class); + + private ExtentTestActions() { + + } + + public static void log(Status logStatus, Markup mark) { + ExtentTest test = testManager.getTest(); + test.log(logStatus, mark); + } + + public static void log(Status logStatus, String message) { + ExtentTest test = testManager.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 = testManager.getTest(); + test.log(logStatus, throwabel); + } + + 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 Optional<String> takeScreenshot(final Status logStatus, final String screenshotName, + final String message) { + try { + return Optional.of(addScreenshot(logStatus, screenshotName, message)); + } catch (final IOException e) { + LOGGER.warn("Could not take screenshot", e); + } + + return Optional.empty(); + } + + public static String addScreenshot(final Status logStatus, String screenshotName, + final String message) throws IOException { + final String[] splitUuid = UUID.randomUUID().toString().split("-"); + screenshotName = screenshotName + "-" + splitUuid[splitUuid.length - 1]; + final File imageFile = GeneralUIUtils.takeScreenshot(screenshotName, SetupCDTest.getScreenshotFolder()); + final String imageFilePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFile.toURI()) + .getPath(); + testManager.getTest() + .log(logStatus, message, MediaEntityBuilder.createScreenCaptureFromPath(imageFilePath).build()); + return imageFilePath; + } + + private static String addDurationTag(String duration) { + return "<td width=\"80px\">" + duration + "</td>"; + } + + private static String addLinkTag(String fileName, String pathToFile) { + return String.format("<a download=\"%s\" href=\"%s\">HAR file</a>", fileName, pathToFile); + } + + static void addFileToReportAsLink(File harFile, String pathToFileFromReportDirectory, String message) { + log(Status.INFO, message, addLinkTag(harFile.getName(), pathToFileFromReportDirectory)); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentTestManager.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentTestManager.java new file mode 100644 index 0000000000..2d194ba5e7 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ExtentTestManager.java @@ -0,0 +1,70 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import com.aventstack.extentreports.ExtentReports; +import com.aventstack.extentreports.ExtentTest; +import org.onap.sdc.backend.ci.tests.api.SomeInterface; + +import java.util.HashMap; + +public class ExtentTestManager implements SomeInterface { + + private final HashMap<Long, ExtentTest> extentTestByThreadIdMap = new HashMap<>(); + private final ExtentReports extent = ExtentManager.getReporter(); + private static final ExtentTestManager INSTANCE = new ExtentTestManager(); + + private ExtentTestManager() { + + } + + public static ExtentTestManager getInstance() { + return INSTANCE; + } + + @Override + public synchronized ExtentTest getTest() { + return extentTestByThreadIdMap.get(Thread.currentThread().getId()); + } + + public synchronized void endTest() { + extent.flush(); + } + + public synchronized ExtentTest startTest(final String testName) { + return startTest(testName, ""); + } + + public synchronized ExtentTest startTest(final String testName, final String desc) { + final ExtentTest test = extent.createTest(testName, desc); + extentTestByThreadIdMap.put(Thread.currentThread().getId(), test); + + return test; + } + + public synchronized <T> void assignCategory(Class<T> clazz) { + String[] parts = clazz.getName().split("\\."); + String lastOne1 = parts[parts.length - 1]; + String lastOne2 = parts[parts.length - 2]; + extentTestByThreadIdMap.get(Thread.currentThread().getId()).assignCategory(lastOne2 + "-" + lastOne1); + } +} + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/MobProxy.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/MobProxy.java new file mode 100644 index 0000000000..8af26eb6b9 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/MobProxy.java @@ -0,0 +1,132 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import com.github.markusbernhardt.proxy.ProxySearch; +import com.github.markusbernhardt.proxy.ProxySearch.Strategy; +import com.github.markusbernhardt.proxy.util.PlatformUtil; +import com.github.markusbernhardt.proxy.util.PlatformUtil.Platform; +import net.lightbody.bmp.BrowserMobProxyServer; +import org.apache.http.HttpStatus; +import org.slf4j.LoggerFactory; + +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.HashMap; +import java.util.List; + +public class MobProxy { + + private static HashMap<Long, BrowserMobProxyServer> mobProxyServerMap = new HashMap<Long, BrowserMobProxyServer>(); + private static InetSocketAddress localProxyAddress = getProxy(); + + public static InetSocketAddress getProxy() { + setLogger(); + + ProxySearch proxySearch = new ProxySearch(); + if (PlatformUtil.getCurrentPlattform() == Platform.WIN) { + proxySearch.addStrategy(Strategy.IE); + proxySearch.addStrategy(Strategy.FIREFOX); + proxySearch.addStrategy(Strategy.JAVA); + } else if (PlatformUtil.getCurrentPlattform() == Platform.LINUX) { + proxySearch.addStrategy(Strategy.GNOME); + proxySearch.addStrategy(Strategy.KDE); + proxySearch.addStrategy(Strategy.FIREFOX); + proxySearch.addStrategy(Strategy.ENV_VAR); + return null; + } else { + proxySearch.addStrategy(Strategy.OS_DEFAULT); + } + ProxySelector proxySelector = proxySearch.getProxySelector(); + + ProxySelector.setDefault(proxySelector); + URI home = URI.create("http://www.google.com"); + System.out.println("ProxySelector: " + proxySelector); + System.out.println("URI: " + home); + List<Proxy> proxyList = proxySelector.select(home); + String host = null; + String port = null; + if (proxyList != null && !proxyList.isEmpty()) { + for (Proxy proxy : proxyList) { + System.out.println(proxy); + SocketAddress address = proxy.address(); + if (address instanceof InetSocketAddress) { + host = ((InetSocketAddress) address).getHostName(); + port = Integer.toString(((InetSocketAddress) address).getPort()); + System.setProperty("http.proxyHost", host); + System.setProperty("http.proxyPort", port); + } + } + } + InetSocketAddress address = new InetSocketAddress(host, Integer.parseInt(port)); + return address; + } + + // set logger for all classes connected to MobProxy + public static void setLogger() { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + for (Logger logger : lc.getLoggerList()) { + logger.setLevel(Level.INFO); + } + } + + public static synchronized void setProxyServer() { + BrowserMobProxyServer server = new BrowserMobProxyServer(); + server.setTrustAllServers(true); + if (localProxyAddress != null) { + server.setChainedProxy(localProxyAddress); + server.start(); + } else { + server.start(); + // filter firefox requests to mozilla when system proxy is absent + server.blacklistRequests(".*mozilla.*", HttpStatus.SC_OK); + } + addProxyServerToPull(Thread.currentThread().getId(), server); + } + + public static synchronized BrowserMobProxyServer getPoxyServer() { + return mobProxyServerMap.get(Thread.currentThread().getId()); + } + + public static void addProxyServerToPull(Long threadId, BrowserMobProxyServer server) { + mobProxyServerMap.put(threadId, server); + } + + public static synchronized void removePoxyServer() { + if (getPoxyServer() != null) { + getPoxyServer().stop(); + mobProxyServerMap.remove(Thread.currentThread().getId()); + } + } + + public static void removeAllProxyServers() { + for (Long threadNumber : mobProxyServerMap.keySet()) { + mobProxyServerMap.get(threadNumber).stop(); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/OnboardCSVReport.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/OnboardCSVReport.java new file mode 100644 index 0000000000..2029eeeef6 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/OnboardCSVReport.java @@ -0,0 +1,63 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.PrintWriter; + +public class OnboardCSVReport { + + private StringBuilder sb; + private PrintWriter pw; + + public OnboardCSVReport(String filepath, String filename) { + sb = new StringBuilder(); + try { + File csvFile = new File(filepath + filename); + pw = new PrintWriter(csvFile); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + + } + + public StringBuilder appendStringToFile(String content) { + return sb.append(content + ","); + } + + public void openNewRow() { + sb.append("\n"); + } + + public void writeRow(String... content) { + for (String str : content) { + appendStringToFile(str); + } + openNewRow(); + } + + public void closeFile() { + pw.write(sb.toString()); + pw.close(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ReportAfterTestManager.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ReportAfterTestManager.java new file mode 100644 index 0000000000..9d2631510e --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/ReportAfterTestManager.java @@ -0,0 +1,124 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import com.aventstack.extentreports.Status; +import org.apache.commons.lang3.StringUtils; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentManager.suiteNameXml; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.ITestContext; +import org.testng.ITestResult; + +import java.io.IOException; + +import static org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions.addScreenshot; +import static org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions.addTag; +import static org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions.log; + +public class ReportAfterTestManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(ReportAfterTestManager.class); + private static String testName; + private static Throwable throwable; + private static String exceptionMsgFormat = "%s - The following exception occurred:"; + + private ReportAfterTestManager() { + + } + + public static void report(final ITestResult result, final ITestContext context) { + testName = result.getName(); + throwable = result.getThrowable(); + + final String suiteName = ExtentManager.getSuiteName(context); + + switch (result.getStatus()) { + case ITestResult.SUCCESS: + logSuccessAfterTest(); + break; + + case ITestResult.FAILURE: + logFailure(suiteName); + break; + + case ITestResult.SKIP: + logSkipAfterTest(); + break; + + default: + break; + } + + } + + private static void logSuccessAfterTest() { + addTag(Status.PASS, "Success"); + takeScreenshot(Status.PASS); + } + + private static void logFailAfterTest() { + addTag(Status.FAIL, "Failure"); + log(Status.ERROR, String.format(exceptionMsgFormat, Status.ERROR)); + log(Status.ERROR, throwable); + takeScreenshot(Status.FAIL); + } + + private static void logSkipAfterTest() { + addTag(Status.SKIP, "Skipped"); + log(Status.SKIP, String.format(exceptionMsgFormat, Status.SKIP)); + log(Status.SKIP, throwable); + takeScreenshot(Status.SKIP); + } + + private static void logFatalAfterTest() { + addTag(Status.FATAL, "Fatal"); + log(Status.FATAL, String.format(exceptionMsgFormat, Status.FATAL)); + log(Status.FATAL, throwable); + takeScreenshot(Status.FATAL); + } + + private static void takeScreenshot(final Status status) { + String adjustedTestName = testName; + String infoFromDataProvider = WindowTestManager.getWindowMap().getAddedValueFromDataProvider(); + if (StringUtils.isNotEmpty(infoFromDataProvider)) { + infoFromDataProvider = infoFromDataProvider.replace(":", "-"); + adjustedTestName = String.format("%s | %s", testName, infoFromDataProvider); + } + try { + addScreenshot(status, adjustedTestName, "Finished the test with the following screenshot:"); + } catch (final IOException e) { + final String warnMsg = "Could not take screenshot of the final screen"; + LOGGER.warn(warnMsg, e); + log(Status.WARNING, String.format("%s: %s", warnMsg, e.getMessage())); + } + } + + private static void logFailure(final String suiteName) { + if (suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName)) { + logFatalAfterTest(); + } else { + logFailAfterTest(); + } + } + +} + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/Retry.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/Retry.java new file mode 100644 index 0000000000..1e9d9e4603 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/Retry.java @@ -0,0 +1,40 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import org.testng.IRetryAnalyzer; +import org.testng.ITestResult; + +public class Retry implements IRetryAnalyzer { + private int retryCount = 0; + private int maxRetryCount = 1; + + public boolean retry(ITestResult result) { + + if (retryCount < maxRetryCount) { + retryCount++; + return true; + } + return false; + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/SetupCDTest.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/SetupCDTest.java new file mode 100644 index 0000000000..9f5a7cc7cd --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/SetupCDTest.java @@ -0,0 +1,487 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.LoggerContext; +import com.aventstack.extentreports.ExtentTest; +import com.aventstack.extentreports.Status; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.Arrays; +import java.util.UUID; +import net.lightbody.bmp.core.har.Har; +import org.json.simple.JSONObject; +import org.onap.sdc.backend.ci.tests.config.UserCredentialsFromFile; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.UserCredentials; +import org.onap.sdc.frontend.ci.tests.execute.sanity.OnboardingFlowsUi; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.AutomationUtils; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.testng.Assert; +import org.testng.ITestContext; +import org.testng.ITestResult; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Optional; +import org.testng.annotations.Parameters; +import org.testng.annotations.Test; + +public abstract class SetupCDTest extends DriverFactory { + + private static final Logger LOGGER = LoggerFactory.getLogger(SetupCDTest.class); + + private static final String RE_RUN = "<html><font color=\"red\">ReRun - </font></html>"; + private static final String WEB_SEAL_PASSWORD = "123123a"; + protected static final String HEAT_FILE_YAML_NAME_PREFIX = "Heat-File"; + protected static final String HEAT_FILE_YAML_NAME_SUFFIX = ".yaml"; + private static final int BASIC_SLEEP_DURATION = 1000; + + /**************** CONSTANTS ****************/ + private static final String CREDENTIALS_FILE = "credentials.yaml"; + + private static final String REPORT_FILE_NAME = "SDC_UI_Extent_Report.html"; + private static final String REPORT_FOLDER = "target" + File.separator + "ExtentReport" + File.separator; + private static final String SCREENSHOT_FOLDER = REPORT_FOLDER + "screenshots" + File.separator; + private static final String HAR_FILES_FOLDER_NAME = "har_files"; + private static final String HAR_FILES_FOLDER = REPORT_FOLDER + HAR_FILES_FOLDER_NAME + File.separator; + + private static final String SHORT_CSV_REPORT_FILE_NAME = "ShortReport.csv"; + + private static final int NUM_OF_ATTEMPTS_TO_REFTRESH = 2; + + /**************** PRIVATES ****************/ + private static String url; + + private static boolean uiSimulator; + private static boolean localEnv = true; + private static OnboardCSVReport csvReport; + private final UserCredentialsFromFile credentialsIns = UserCredentialsFromFile.getInstance(); + private static ITestContext myContext; + + public SetupCDTest() { + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + lc.getLogger("org.apache").setLevel(Level.INFO); + } + + public static ExtentTest getExtendTest() { + return ExtentTestManager.getInstance().getTest(); + } + + public static WindowTest getWindowTest() { + return WindowTestManager.getWindowMap(); + } + + private OnboardCSVReport getCsvReport() { + return csvReport; + } + + public static String getReportFolder() { + return REPORT_FOLDER; + } + + public static String getScreenshotFolder() { + return SCREENSHOT_FOLDER; + } + + private static String getHarFilesFolder() { + return HAR_FILES_FOLDER; + } + + + protected abstract UserRoleEnum getRole(); + + /**************** BEFORE ****************/ + + @BeforeSuite(alwaysRun = true) + public void setupBeforeSuite(ITestContext context) throws Exception { + RestCDUtils.deleteOnDemand(); + myContext = context; + setUrl(); + ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context); + csvReport = new OnboardCSVReport(getReportFolder(), SHORT_CSV_REPORT_FILE_NAME); + } + + @BeforeMethod(alwaysRun = true) + 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); + if (suiteName.equals(ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) { + ExtentTestManager.getInstance().startTest(RE_RUN + method.getName()); + } else { + ExtentTestManager.getInstance().startTest(method.getName()); + } + + ExtentTestManager.getInstance().assignCategory(this.getClass()); + setBrowserBeforeTest(getRole()); + } else { + System.out.println("ExtentReport instance started from Test..."); + } + + if (getConfig().getCaptureTraffic()) { + try { + MobProxy.getPoxyServer().newHar(method.getName() + ".har"); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + /**************** AFTER ****************/ + @AfterMethod(alwaysRun = true) + public void quitAfterTest(final ITestResult result, final ITestContext context) throws Exception { + try { + ReportAfterTestManager.report(result, context); + GeneralUIUtils.closeErrorMessage(); + } finally { + try { + if (getConfig().getCaptureTraffic()) { + addTrafficFileToReport(result); + } + + if (result.getInstanceName().equals(OnboardingFlowsUi.class.getName()) && result.getStatus() == ITestResult.FAILURE) { + final String msg = "Onboarding test failed, closing browser"; + LOGGER.info(msg); + getExtendTest().log(Status.INFO, msg); + quitDriver(); + } else if (!getUser().getRole().toLowerCase().equals(UserRoleEnum.ADMIN.name().toLowerCase())) { + boolean navigateToHomePageSuccess = HomePage.navigateToHomePage(); + if (!navigateToHomePageSuccess) { + final String msg = "Navigating to homepage failed, reopening driver"; + LOGGER.info(msg); + getExtendTest().log(Status.INFO, msg); + quitDriver(); + } + } + + } catch (final Exception e) { + LOGGER.error("An unexpected error has occurred", e); + getExtendTest().log(Status.ERROR, "Exception:" + e.toString()); + } + + + ExtentTestManager.getInstance().endTest(); + final String suiteName = ExtentManager.getSuiteName(context); +// write result to csv file + if ((!ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName)) && (result.getStatus() == ITestResult.SKIP)) { + addResultToCSV(result, context); + } + if (ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName) && !(result.getStatus() == ITestResult.SUCCESS)) { + addResultToCSV(result, context); + } + FileHandling.cleanCurrentDownloadDir(); + } + + } + + private void addResultToCSV(ITestResult result, ITestContext context) { + ExtentTest test = getExtendTest(); + com.aventstack.extentreports.model.Test model = test.getModel(); + String name = model.getName(); + String status = model.getStatus().toString(); + getCsvReport().writeRow(result.getInstanceName(), name.replace(RE_RUN, ""), status); + } + + private void generateReport4Jenkins(ITestContext context) { + final String suiteName = ExtentManager.getSuiteName(context); + final JSONObject obj = new JSONObject(); + final String success = Integer.toString(context.getPassedTests().size()); + final String failed = Integer.toString(context.getFailedTests().size()); + final String total = Integer.toString(context.getFailedTests().size() + context.getPassedTests().size()); + obj.put("projectName", "SDC-ONAP-UI-Automation-" + suiteName); + obj.put("projectVersion", AutomationUtils.getOSVersion()); + obj.put("platform", "Linux"); + obj.put("total", total); + obj.put("success", success); + obj.put("failed", failed); + + try (FileWriter file = new FileWriter(getReportFolder() + "jenkinsResults.json")) { + file.write(obj.toJSONString()); + file.flush(); + } catch (final IOException e) { + LOGGER.debug("An error has occurred while writing 'jenkinsResults.json' file", e); + } + + LOGGER.debug(obj.toJSONString()); + } + + + @Parameters({"eraseAfterTests"}) + @AfterSuite(alwaysRun = true) + public void afterSuite2(@Optional("true") String eraseAfterTestsReadValue) throws Exception { + + csvReport.closeFile(); + generateReport4Jenkins(myContext); + + if (Boolean.parseBoolean(eraseAfterTestsReadValue)) { + RestCDUtils.deleteOnDemand(); + } else { + System.out.println("Resources will not be deleted according to suite configuration ..."); + } + + if (getConfig().getUseBrowserMobProxy()) { + MobProxy.getPoxyServer().stop(); + } + } + + private static String setUrl() { + url = getConfig().getUrl(); + uiSimulator = getConfig().isUiSimulator(); + if (url == null) { + String message = "no URL found"; + System.out.println(message); + Assert.fail(message); + } else if (!url.contains("localhost") && !url.contains("192.168.33.10") && !url.contains("127.0.0.1") && !url.contains("192.168.50.5") && !uiSimulator) { + localEnv = false; + } + return url; + } + + + private static void navigateToUrl(final String url) { + try { + LOGGER.info("Deleting cookies"); + deleteCookies(); + LOGGER.info("Navigating to URL : " + url); + getDriver().navigate().to(url); + GeneralUIUtils.waitForLoader(); + LOGGER.info("Zooming out"); + GeneralUIUtils.windowZoomOutUltimate(); + } catch (Exception e) { + final String errorMsg = String.format("Could not navigate to '%s'", url); + LOGGER.error(errorMsg, e); + getExtendTest().log(Status.ERROR, errorMsg); + Assert.fail(errorMsg); + } + } + + private static void deleteCookies() throws Exception { + getDriver().manage().deleteAllCookies(); + Thread.sleep(BASIC_SLEEP_DURATION); + + int attempts = 0; + final int max_attempts = 3; + + while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts) { + getExtendTest().log(Status.INFO, "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts"); + String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });"; + ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS); + attempts++; + + if (attempts == max_attempts) { + String msg = "Did not delete cookies, can't login as user " + WindowTestManager.getWindowMap().getUser().getRole(); + System.out.println(msg); + getExtendTest().log(Status.ERROR, msg); + Assert.fail(msg); + } + } + } + + private void loginToSystem(UserRoleEnum role) throws Exception { + final int gettingWebElementTimeOut = 30; + UserCredentials credentials = new UserCredentials(role.getUserId(), role.getPassword(), role.getFirstName(), role.getLastName(), role.name()); + if (localEnv) { + loginToSimulator(role); + } else { + sendUserAndPasswordKeys(credentials); + WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), gettingWebElementTimeOut); + submitButton.click(); + WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), gettingWebElementTimeOut); + Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed."); + buttonOK.click(); + } + GeneralUIUtils.ultimateWait(); + getWindowTest().setUser(credentials); + } + + private void goToHomePage(UserRoleEnum role) throws Exception { + final int gettingButtonTimeOut = 10; + try { + getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() == 0 ? NUM_OF_ATTEMPTS_TO_REFTRESH : getWindowTest().getRefreshAttempts()); + if (!role.equals(UserRoleEnum.ADMIN)) { + + WebElement closeButton = GeneralUIUtils.getClickableButtonBy(By.className("sdc-welcome-close"), gettingButtonTimeOut); + if (closeButton != null) { + closeButton.click(); + } + + if (!GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue())) { + restartBrowser(role); + } + } + } catch (Exception e) { + restartBrowser(role); + } + } + + private void restartBrowser(UserRoleEnum role) throws Exception { + getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() - 1); + if (getWindowTest().getRefreshAttempts() <= 0) { + System.out.println("ERR : Something is wrong with browser!"); + Assert.fail("ERR : Something is wrong with browser!"); + } + System.out.println("Trying again..."); + getExtendTest().log(Status.INFO, "Trying again..."); + getExtendTest().log(Status.INFO, String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts())); + System.out.println(String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts())); + + reloginWithNewRole(role); + } + + private void loginToSimulator(UserRoleEnum role) { + final int gettingWebElementTimeOut = 30; + WebDriver driver = GeneralUIUtils.getDriver(); + WebDriverWait wait = new WebDriverWait(driver, gettingWebElementTimeOut); + + wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']")))); + + WebElement userIdTextbox = GeneralUIUtils.getWebElementBy(By.name("userId")); + userIdTextbox.sendKeys(role.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password")); + passwordTextbox.sendKeys(WEB_SEAL_PASSWORD); + + wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click(); + } + + private void sendUserAndPasswordKeys(UserCredentials userId) { + System.out.println("Login as user : " + userId.getUserId()); + WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid")); + userNameTextbox.sendKeys(userId.getUserId()); + WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password")); + passwordTextbox.sendKeys(userId.getPassword()); + } + + private void loginWithUser(final UserRoleEnum role) { + try { + final String msg = String + .format("Login as user '%s', role '%s'", role.getUserId(), role.getUserRole()); + getExtendTest().log(Status.INFO, msg); + LOGGER.info(msg); + loginToSystem(role); + LOGGER.debug("Going to home page"); + goToHomePage(role); + } catch (final Exception e) { + throw new RuntimeException(e); + } finally { + getWindowTest().setPreviousRole(getWindowTest().getUser().getRole()); + } + } + + private void setUser(UserRoleEnum role) { + User user = new User(); + user.setUserId(role.getUserId()); + user.setFirstName(role.getFirstName()); + user.setRole(role.name()); + user.setLastName(role.getLastName()); + + getWindowTest().setUser(user); + } + + public User getUser() { + return getWindowTest().getUser(); + } + + private void setBrowserBeforeTest(final UserRoleEnum role) { + LOGGER.info(String.format("Setup before test for role '%s'", role.name())); + if (!getWindowTest().getPreviousRole().equalsIgnoreCase(role.name())) { + LOGGER.info(String.format("Logging in with new role '%s'. Previous role was: '%s'.", role.name(), + getWindowTest().getPreviousRole())); + navigateAndLogin(role); + } + } + + private void navigateAndLogin(final UserRoleEnum role) { + getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts()); + setUser(role); + navigateToUrl(url); + loginWithUser(role); + GeneralUIUtils.ultimateWait(); + } + + public User getUser(UserRoleEnum role) { + User user = new User(); + user.setUserId(role.getUserId()); + user.setFirstName(role.getFirstName()); + user.setLastName(role.getLastName()); + user.setRole(role.name()); + return user; + } + + protected void reloginWithNewRole(final UserRoleEnum role) { + navigateAndLogin(role); + } + + private void addTrafficFileToReport(ITestResult result) { + try { + // Get the HAR data + Har har = MobProxy.getPoxyServer().getHar(); + String shortUUID = UUID.randomUUID().toString().split("-")[0]; + File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har"); + new File(getHarFilesFolder()).mkdirs(); + + har.writeTo(harFile); + + String pathToFileFromReportDirectory = HAR_FILES_FOLDER_NAME + File.separator + harFile.getName(); + ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory, "File with captured traffic"); + } catch (IOException ioe) { + ioe.printStackTrace(); + } + } + + /* + * * Start section of test in ExtentReport with DataProvider parameters, + * should be started from test method, see example in onboardVNFTest + */ + public void setLog(String fromDataProvider) { + + String suiteName = ExtentManager.getSuiteName(myContext); + if (ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName)) { + ExtentTestManager.getInstance().startTest(RE_RUN + Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider); + } else { + ExtentTestManager.getInstance().startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider); + } + + + getWindowTest().setAddedValueFromDataProvider(fromDataProvider); + ExtentTestManager.getInstance().assignCategory(this.getClass()); + setBrowserBeforeTest(getRole()); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/TestFtp.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/TestFtp.java new file mode 100644 index 0000000000..e4159600a3 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/TestFtp.java @@ -0,0 +1,92 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; + +public class TestFtp { + + public static void main(String[] args) throws IOException { + AttFtpClient instance = AttFtpClient.getFtpClient(); + + String server = "localhost"; + final int port = 2121; + String user = "admin"; + String pass = "admin"; + AttFtpClient.getFtpClient().init(server, port, user, pass); + + try { + AttFtpClient.getFtpClient().retrieveListOfFile(); + + File retrieveLastModifiedFileFromFTP = instance.retrieveLastModifiedFileFromFTP(); + String content = new String(Files.readAllBytes(Paths.get(retrieveLastModifiedFileFromFTP.getPath())), StandardCharsets.UTF_8); +// instance.deleteFilesFromFTPserver(); + System.out.println(content); + readFile(retrieveLastModifiedFileFromFTP); + + } finally { + instance.terminateClient(); + } + + + } + + private static void readFile(File retrieveLastModifiedFileFromFTP) { + + StringBuilder sb = new StringBuilder(); + BufferedReader br = null; + FileReader fileReader = null; + try { + fileReader = new FileReader(retrieveLastModifiedFileFromFTP.getPath()); + br = new BufferedReader(fileReader); + String line; + while ((line = br.readLine()) != null) { + if (sb.length() > 0) { + sb.append("\n"); + } + sb.append(line); + } + } catch (IOException e) { + System.out.println(e); + } finally { + try { + if (br != null) { + br.close(); + } + if (fileReader != null) { + fileReader.close(); + } + } catch (IOException ex) { + System.out.println(ex); + } + } + String contents = sb.toString(); + System.out.println(contents); + + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WebDriverThread.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WebDriverThread.java new file mode 100644 index 0000000000..afc8524751 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WebDriverThread.java @@ -0,0 +1,125 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import net.lightbody.bmp.BrowserMobProxyServer; +import net.lightbody.bmp.client.ClientUtil; +import net.lightbody.bmp.proxy.CaptureType; +import org.onap.sdc.backend.ci.tests.config.Config; +import org.onap.sdc.frontend.ci.tests.exception.WebDriverThreadRuntimeException; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.openqa.selenium.Dimension; +import org.openqa.selenium.Platform; +import org.openqa.selenium.UnexpectedAlertBehaviour; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.firefox.FirefoxOptions; +import org.openqa.selenium.firefox.FirefoxProfile; +import org.openqa.selenium.remote.CapabilityType; +import org.openqa.selenium.remote.DesiredCapabilities; +import org.openqa.selenium.remote.LocalFileDetector; +import org.openqa.selenium.remote.RemoteWebDriver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.UUID; + +public class WebDriverThread { + + private final static Logger LOGGER = LoggerFactory.getLogger(SetupCDTest.class); + + private WebDriver webdriver; + private FirefoxProfile firefoxProfile; + private static final String SELENIUM_NODE_URL = "http://%s:%s/wd/hub"; + + WebDriverThread(Config config) { + initDriver(config); + webdriver.manage().window().maximize(); + } + + public WebDriver getDriver() { + return webdriver; + } + + void quitDriver() { + if (webdriver != null) { + webdriver.quit(); + webdriver = null; + } + } + + + private void initDriver(final Config config) { + if (config.isRemoteTesting()) { + LOGGER.info("Opening REMOTE browser"); + final String remoteEnvIP = config.getRemoteTestingMachineIP(); + final String remoteEnvPort = config.getRemoteTestingMachinePort(); + FirefoxOptions firefoxOptions = new FirefoxOptions(); + firefoxOptions.setProfile(initFirefoxProfile(config)); + firefoxOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); + final String remoteUrlString = String.format(SELENIUM_NODE_URL, remoteEnvIP, remoteEnvPort); + final URL remoteUrl; + try { + remoteUrl = new URL(remoteUrlString); + } catch (MalformedURLException e) { + throw new WebDriverThreadRuntimeException(String.format("Malformed URL '%s'", remoteUrlString), e); + } + final RemoteWebDriver remoteWebDriver = new RemoteWebDriver(remoteUrl, firefoxOptions); + remoteWebDriver.setFileDetector(new LocalFileDetector()); + remoteWebDriver.manage().window().setSize(new Dimension(1920,1440)); + webdriver = remoteWebDriver; + + } else { + LOGGER.info("Opening LOCAL browser"); + System.setProperty("webdriver.gecko.driver", "target/gecko/geckodriver"); + FirefoxOptions firefoxOptions = new FirefoxOptions(); + firefoxOptions.setProfile(initFirefoxProfile(config)); + firefoxOptions.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); + firefoxOptions.setHeadless(false); + webdriver = new FirefoxDriver(firefoxOptions); + webdriver.manage().window().maximize(); + } + } + + private FirefoxProfile initFirefoxProfile(Config config) { + firefoxProfile = new FirefoxProfile(); + firefoxProfile.setPreference("browser.download.folderList", 0); + //firefoxProfile.setPreference("browser.alwaysOpenInSystemViewerContextMenuItem", false); + //firefoxProfile.setPreference("browser.download.useDownloadDir", false); + //firefoxProfile.setPreference("browser.download.downloadDir", config.getContainerDownloadAutomationFolder()); + //firefoxProfile.setPreference("browser.download.dir", config.getContainerDownloadAutomationFolder()); + //firefoxProfile.setPreference("app.update.notifyDuringDownload", false); + //firefoxProfile.setPreference("browser.download.lastDir", config.getContainerDownloadAutomationFolder()); + firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/octet-stream, application/xml, text/plain, text/xml, image/jpeg"); + firefoxProfile.setPreference("network.proxy.type", 4); + firefoxProfile.setAcceptUntrustedCertificates(true); + firefoxProfile.setAssumeUntrustedCertificateIssuer(true); + + return firefoxProfile; + } + + FirefoxProfile getFirefoxProfile() { + return firefoxProfile; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WindowTest.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WindowTest.java new file mode 100644 index 0000000000..351b3a88d2 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WindowTest.java @@ -0,0 +1,83 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import org.onap.sdc.backend.ci.tests.config.Config; +import org.openecomp.sdc.be.model.User; + +import java.io.File; + +public class WindowTest { + + public WindowTest() { + refreshAttempts = 0; + previousRole = ""; + addedValueFromDataProvider = null; + downloadDirectory = Config.instance().getDownloadAutomationFolder(); + } + + private int refreshAttempts; + private String previousRole; + private User user; + private String addedValueFromDataProvider; + private String downloadDirectory; + + public int getRefreshAttempts() { + return refreshAttempts; + } + + public void setRefreshAttempts(int refreshAttempts) { + this.refreshAttempts = refreshAttempts; + } + + public String getPreviousRole() { + return previousRole; + } + + public void setPreviousRole(String previousRole) { + this.previousRole = previousRole; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } + + public synchronized String getAddedValueFromDataProvider() { + return addedValueFromDataProvider; + } + + public synchronized void setAddedValueFromDataProvider(String addedValueFromDataProvider) { + this.addedValueFromDataProvider = addedValueFromDataProvider; + } + + public String getDownloadDirectory() { + return downloadDirectory; + } + + public void setDownloadDirectory(String downloadDirectory) { + this.downloadDirectory = downloadDirectory; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WindowTestManager.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WindowTestManager.java new file mode 100644 index 0000000000..c38e4d71f0 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/execute/setup/WindowTestManager.java @@ -0,0 +1,50 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.execute.setup; + +import java.util.HashMap; + +public class WindowTestManager { + + private static HashMap<Long, WindowTest> windowMap = new HashMap<Long, WindowTest>(); + + public static synchronized WindowTest getWindowMap() { + Long currentThreadId = Thread.currentThread().getId(); + boolean containsKey = windowMap.containsKey(currentThreadId); + if (!containsKey) { + setWindowMap(currentThreadId); + } + return windowMap.get(currentThreadId); + } + + private static synchronized void setWindowMap(Long currentThreadId) { + WindowTestManager.windowMap.put(currentThreadId, new WindowTest()); + } + + public static synchronized void removeWindowTest() { + windowMap.remove(Thread.currentThread().getId()); + } + + public static synchronized HashMap<Long, WindowTest> getWholeMap() { + return windowMap; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/AbstractUiTestFlow.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/AbstractUiTestFlow.java new file mode 100644 index 0000000000..30cfd2e0bd --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/AbstractUiTestFlow.java @@ -0,0 +1,48 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow; + +import com.aventstack.extentreports.ExtentTest; +import org.onap.sdc.frontend.ci.tests.flow.exception.MissingParameterRuntimeException; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestManager; +import org.onap.sdc.frontend.ci.tests.pages.PageObject; +import org.openqa.selenium.WebDriver; + +public abstract class AbstractUiTestFlow implements UiTestFlow { + + protected final WebDriver webDriver; + protected final ExtentTest extendTest = ExtentTestManager.getInstance().getTest(); + + public AbstractUiTestFlow(final WebDriver webDriver) { + this.webDriver = webDriver; + } + + public <T extends PageObject> T findParameter(final PageObject[] pageObjects, + final Class<T> expectedParameterType) { + for (final PageObject uiTestFlow : pageObjects) { + if(expectedParameterType.isInstance(uiTestFlow)) { + return (T) uiTestFlow; + } + } + + throw new MissingParameterRuntimeException(expectedParameterType.getName()); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CheckSoftwareVersionPropertyFlow.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CheckSoftwareVersionPropertyFlow.java new file mode 100644 index 0000000000..3b161546c9 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CheckSoftwareVersionPropertyFlow.java @@ -0,0 +1,102 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage; +import org.onap.sdc.frontend.ci.tests.pages.PageObject; +import org.onap.sdc.frontend.ci.tests.pages.ResourceLeftSideMenu; +import org.openqa.selenium.WebDriver; + +import java.util.List; +import java.util.Optional; + +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.hasSize; +import static org.junit.Assert.assertThat; + +/** + * UI Flow for checking the software version property in a resource + */ +public class CheckSoftwareVersionPropertyFlow extends AbstractUiTestFlow { + + private final List<String> expectedSoftwareVersionList; + + public CheckSoftwareVersionPropertyFlow(final WebDriver webDriver, final List<String> expectedSoftwareVersionList) { + super(webDriver); + this.expectedSoftwareVersionList = expectedSoftwareVersionList; + } + + @Override + public Optional<PageObject> run(final PageObject... pageObjects) { + final ResourceLeftSideMenu resourceLeftSideMenu = new ResourceLeftSideMenu(webDriver); + resourceLeftSideMenu.isLoaded(); + + final ResourcePropertiesAssignmentPage resourcePropertiesAssignmentPage = accessPropertiesAssignmentPage(); + + checkSoftwareVersionProperty(resourcePropertiesAssignmentPage); + return Optional.empty(); + } + + /** + * Checks if the software_version property values are as expected by the {@link #expectedSoftwareVersionList}. + * + * @param resourcePropertiesAssignmentPage the resource properties assignment page + */ + private void checkSoftwareVersionProperty(final ResourcePropertiesAssignmentPage resourcePropertiesAssignmentPage) { + extendTest.log(Status.INFO, + String.format("Checking the presence of software versions '%s' in 'software_versions' property", + getSoftwareVersionListAsString()) + ); + final List<String> actualSoftwareVersionList = resourcePropertiesAssignmentPage.getSoftwareVersionProperty(); + assertThat("Software Version should have the expected size", actualSoftwareVersionList, + hasSize(expectedSoftwareVersionList.size())); + assertThat("Software Version should be as expected", actualSoftwareVersionList, + containsInAnyOrder(expectedSoftwareVersionList.toArray(new String[0]))); + } + + /** + * Accesses the properties assignment page by clicking in the resource left side menu. + * + * @return the resulting resource properties assignment page + */ + private ResourcePropertiesAssignmentPage accessPropertiesAssignmentPage() { + final ResourceLeftSideMenu resourceLeftSideMenu = new ResourceLeftSideMenu(webDriver); + resourceLeftSideMenu.isLoaded(); + + extendTest.log(Status.INFO, + String.format("Accessing the Properties Assignment page to check the software versions '%s'", + getSoftwareVersionListAsString()) + ); + final ResourcePropertiesAssignmentPage resourcePropertiesAssignmentPage = + resourceLeftSideMenu.clickOnPropertiesAssignmentMenuItem(); + resourcePropertiesAssignmentPage.isLoaded(); + return resourcePropertiesAssignmentPage; + } + + /** + * Converts the {@link #expectedSoftwareVersionList} in a comma + space separated string. + * + * @return the software version list as a comma + space separated string + */ + private String getSoftwareVersionListAsString() { + return String.join(", ", expectedSoftwareVersionList); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CreateResourceFlow.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CreateResourceFlow.java new file mode 100644 index 0000000000..4b6f3542d2 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CreateResourceFlow.java @@ -0,0 +1,52 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.ResourceCreatePage; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.pages.PageObject; +import org.openqa.selenium.WebDriver; + +import java.util.Optional; + +/** + * UI Flow for Resource creation + */ +public class CreateResourceFlow extends AbstractUiTestFlow { + + private final String resourceName; + + public CreateResourceFlow(final WebDriver webDriver, final String resourceName) { + super(webDriver); + this.resourceName = resourceName; + } + + @Override + public Optional<PageObject> run(final PageObject... pageObjects) { + final ResourceCreatePage resourceCreatePage = findParameter(pageObjects, ResourceCreatePage.class); + extendTest.log(Status.INFO, String.format("Creating the Resource '%s'", resourceName)); + resourceCreatePage.createResource(); + ExtentTestActions.takeScreenshot(Status.INFO, "resource-created", + String.format("Resource '%s' was created", resourceName)); + return Optional.empty(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CreateVspFlow.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CreateVspFlow.java new file mode 100644 index 0000000000..eb80985eba --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/CreateVspFlow.java @@ -0,0 +1,142 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.OnboardHomePage; +import org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding; +import org.onap.sdc.frontend.ci.tests.pages.TopNavComponent; +import org.onap.sdc.frontend.ci.tests.pages.VspCreationModal; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.pages.PageObject; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebDriver; + +import java.util.Optional; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; + +/** + * UI Flow for VSP creation + */ +public class CreateVspFlow extends AbstractUiTestFlow { + + private final String resourceName; + private final String packageFile; + private final String rootFolder; + + public CreateVspFlow(final WebDriver webDriver, final String resourceName, final String packageFile, + final String rootFolder) { + super(webDriver); + this.resourceName = resourceName; + this.packageFile = packageFile; + this.rootFolder = rootFolder; + } + + @Override + public Optional<PageObject> run(final PageObject... pageObjects) { + final TopNavComponent topNavComponent = findParameter(pageObjects, TopNavComponent.class); + extendTest.log(Status.INFO, "Accessing the Onboard Home Page"); + topNavComponent.isLoaded(); + final OnboardHomePage onboardHomePage = goToOnboardHomePage(topNavComponent); + final SoftwareProductOnboarding softwareProductOnboarding = createNewVsp(onboardHomePage); + uploadPackage(softwareProductOnboarding); + submitVsp(softwareProductOnboarding); + goToHomePage(topNavComponent); + return Optional.empty(); + } + + /** + * Goes to the onboard home page by clicking in the onboard tab in the top nav component. + * + * @param topNavComponent the top nav component + * @return the onboard home page + */ + private OnboardHomePage goToOnboardHomePage(final TopNavComponent topNavComponent) { + final OnboardHomePage onboardHomePage = topNavComponent.clickOnOnboard(); + onboardHomePage.isLoaded(); + ExtentTestActions.takeScreenshot(Status.INFO, "onboard-homepage", "Onboard homepage is loaded"); + return onboardHomePage; + } + + /** + * Creates a new VSP in the onboard home page. + * + * @param onboardHomePage the onboard home page representation + * @return the software product onboarding page + */ + private SoftwareProductOnboarding createNewVsp(final OnboardHomePage onboardHomePage) { + extendTest.log(Status.INFO, "Creating a new VSP"); + final VspCreationModal vspCreationModal = onboardHomePage.clickOnCreateNewVsp(); + vspCreationModal.isLoaded(); + vspCreationModal.fillCreationForm(resourceName); + ExtentTestActions.takeScreenshot(Status.INFO, "vsp-creation-form", + "Creating VSP with given information"); + final SoftwareProductOnboarding softwareProductOnboarding = vspCreationModal.clickOnCreate(); + softwareProductOnboarding.isLoaded(); + extendTest.log(Status.INFO, String.format("VSP '%s' created", resourceName)); + final String actualResourceName = softwareProductOnboarding.getResourceName(); + assertThat(String.format("Should be in the Software Product '%s' page", resourceName), + actualResourceName, is(resourceName)); + return softwareProductOnboarding; + } + + /** + * Uploads a package in the software product onboarding page. + * + * @param softwareProductOnboarding the software product onboarding page + */ + private void uploadPackage(final SoftwareProductOnboarding softwareProductOnboarding) { + extendTest.log(Status.INFO, + String.format("Uploading package '%s' to VSP '%s'", packageFile, resourceName) + ); + softwareProductOnboarding.uploadFile(rootFolder + packageFile); + softwareProductOnboarding.attachmentScreenIsLoaded(); + extendTest.log(Status.INFO, + String.format("Package '%s' was uploaded to VSP '%s'.", packageFile, resourceName) + ); + } + + /** + * Submits the VSP through the software product onboarding page. + * + * @param softwareProductOnboarding the software product onboarding page + */ + private void submitVsp(final SoftwareProductOnboarding softwareProductOnboarding) { + extendTest.log(Status.INFO, "Submitting the first VSP version."); + softwareProductOnboarding.submit(); + ExtentTestActions.takeScreenshot(Status.INFO, "vsp-submitted", "The first VSP version was submitted"); + } + + /** + * Go to the system home page through the top nav menu. + * + * @param topNavComponent the top nav component + */ + private void goToHomePage(final TopNavComponent topNavComponent) { + extendTest.log(Status.INFO, "Accessing the Home page to import the created VSP"); + topNavComponent.isLoaded(); + topNavComponent.clickOnHome(); + GeneralUIUtils.ultimateWait(); + topNavComponent.isLoaded(); + ExtentTestActions.takeScreenshot(Status.INFO, "home-is-loaded", "The Home page is loaded."); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/ImportVspFlow.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/ImportVspFlow.java new file mode 100644 index 0000000000..bb9098817e --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/ImportVspFlow.java @@ -0,0 +1,91 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.ResourceCreatePage; +import org.onap.sdc.frontend.ci.tests.pages.TopNavComponent; +import org.onap.sdc.frontend.ci.tests.pages.VspRepositoryModalComponent; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.pages.PageObject; +import org.openqa.selenium.WebDriver; + +import java.util.Optional; + +/** + * UI Flow for importing a VSP + */ +public class ImportVspFlow extends AbstractUiTestFlow { + + private final String resourceName; + + public ImportVspFlow(final WebDriver webDriver, final String resourceName) { + super(webDriver); + this.resourceName = resourceName; + } + + @Override + public Optional<PageObject> run(final PageObject... pageObjects) { + final VspRepositoryModalComponent vspRepositoryModalComponent = openVspRepository(); + searchForVsp(vspRepositoryModalComponent); + return Optional.of(importVsp(vspRepositoryModalComponent)); + } + + /** + * Opens the VSP repository modal by clicking in its icon from the top nav menu. + * + * @return the VSP repository modal + */ + private VspRepositoryModalComponent openVspRepository() { + extendTest.log(Status.INFO, "Opening the VSP repository"); + final TopNavComponent topNavComponent = new TopNavComponent(webDriver); + topNavComponent.isLoaded(); + final VspRepositoryModalComponent vspRepositoryModalComponent = topNavComponent.clickOnRepositoryIcon(); + vspRepositoryModalComponent.isLoaded(); + return vspRepositoryModalComponent; + } + + /** + * Searches for a VSP in the repository modal. + * + * @param vspRepositoryModalComponent the repository modal component + */ + private void searchForVsp(final VspRepositoryModalComponent vspRepositoryModalComponent) { + extendTest.log(Status.INFO, String.format("Searching for VSP '%s' in the repository", resourceName)); + vspRepositoryModalComponent.searchForVSP(resourceName); + ExtentTestActions.takeScreenshot(Status.INFO, "vsp-found-repository", + String.format("Searching for VSP '%s' found in the repository", resourceName)); + } + + /** + * Imports the first VSP in the repository list. + * + * @param vspRepositoryModalComponent the repository modal component that contains the VSP list + * @return the resource creation page that the import action redirects + */ + private ResourceCreatePage importVsp(final VspRepositoryModalComponent vspRepositoryModalComponent) { + extendTest.log(Status.INFO, String.format("Importing VSP '%s'", resourceName)); + final ResourceCreatePage resourceCreatePage = vspRepositoryModalComponent.clickOnImportVsp(1); + resourceCreatePage.isLoaded(); + ExtentTestActions.takeScreenshot(Status.INFO, "vsp-imported", + String.format("VSP '%s' was imported", resourceName)); + return resourceCreatePage; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/UiTestFlow.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/UiTestFlow.java new file mode 100644 index 0000000000..513a62664c --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/UiTestFlow.java @@ -0,0 +1,39 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow; + +import org.onap.sdc.frontend.ci.tests.pages.PageObject; + +import java.util.Optional; + +/** + * Represents a UI test flow + */ +@FunctionalInterface +public interface UiTestFlow { + + /** + * Runs the flow + * @param pageObjects any required page object for the flow + * @return an optional page object representing the page that the flow has ended + */ + Optional<PageObject> run(final PageObject... pageObjects); + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/exception/MissingParameterRuntimeException.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/exception/MissingParameterRuntimeException.java new file mode 100644 index 0000000000..5eee6ebdfb --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/exception/MissingParameterRuntimeException.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow.exception; + +@SuppressWarnings("serial") +public class MissingParameterRuntimeException extends UiTestFlowRuntimeException { + + public MissingParameterRuntimeException(final String parameterName) { + super(String.format("Missing parameter expected %s", parameterName)); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/exception/UiTestFlowRuntimeException.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/exception/UiTestFlowRuntimeException.java new file mode 100644 index 0000000000..4fddbefce2 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/flow/exception/UiTestFlowRuntimeException.java @@ -0,0 +1,28 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.flow.exception; + +@SuppressWarnings("serial") +public class UiTestFlowRuntimeException extends RuntimeException { + + public UiTestFlowRuntimeException(final String s) { + super(s); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/AbstractPageObject.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/AbstractPageObject.java new file mode 100644 index 0000000000..2f13d3bbed --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/AbstractPageObject.java @@ -0,0 +1,166 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import java.util.List; + +/** + * Base UI test object that represents a page or component in a html page + */ +public abstract class AbstractPageObject implements PageObject { + + protected final WebDriver webDriver; + protected int timeoutInSeconds; + + public AbstractPageObject(final WebDriver webDriver) { + this.webDriver = webDriver; + timeoutInSeconds = 10; + } + + /** + * Sets the default timeout for Page Object actions. + */ + public void setTimeout(final int timeoutInSeconds) { + this.timeoutInSeconds = timeoutInSeconds; + } + + /** + * Creates a WebDriverWait instance with the default timeout. + * + * @return a new WebDriverWait instance + */ + protected WebDriverWait getWait() { + return new WebDriverWait(webDriver, timeoutInSeconds); + } + + /** + * Creates a WebDriverWait instance with the provided timeout. + * + * @param timeoutInSeconds the wait timeout in seconds + * @return a new WebDriverWait instance + */ + protected WebDriverWait getWait(final int timeoutInSeconds) { + return new WebDriverWait(webDriver, timeoutInSeconds); + } + + /** + * Find an element based on the provided locator. + * + * @param locator the By locator + * @return the WebElement if found, otherwise throws an exception + */ + protected WebElement findElement(final By locator) { + return webDriver.findElement(locator); + } + + /** + * Find elements based on the provided locator. + * + * @param locator the By locator + * @return the list of WebElement if any found, otherwise throws an exception + */ + protected List<WebElement> findElements(final By locator) { + return webDriver.findElements(locator); + } + + /** + * Find an element inside the provided element using the provided xpath. + * + * @param element the parent element + * @param xpath the xpath expression to search for the internal element + * @return the WebElement if found, otherwise throws an exception + */ + protected WebElement findSubElement(final WebElement element, final String xpath) { + return findSubElement(element, By.xpath(xpath)); + } + + /** + * Find an element inside the provided element using the provided By locator. + * + * @param element the parent element + * @param locator the By locator to search for the internal element + * @return the WebElement if found, otherwise throws an exception + */ + protected WebElement findSubElement(final WebElement element, final By locator) { + return element.findElement(locator); + } + + /** + * Find elements inside the provided element using the provided By locator. + * + * @param element the parent element + * @param locator the By locator to search for the internal element + * @return the list of WebElement if any found, otherwise throws an exception + */ + protected List<WebElement> findSubElements(final WebElement element, final By locator) { + return element.findElements(locator); + } + + /** + * Waits for element visibility with the default timeout. + * + * @param xpath the xpath expression to search for the element + * @return the WebElement if visible before timeout, otherwise throws an exception + */ + protected WebElement waitForElementVisibility(final String xpath) { + return waitForElementVisibility(By.xpath(xpath)); + } + + /** + * Waits for element visibility with the default timeout. + * + * @param locator the By locator to search for the element + * @return the WebElement if visible before timeout, otherwise throws an exception + */ + protected WebElement waitForElementVisibility(final By locator) { + return getWait(timeoutInSeconds) + .until(ExpectedConditions.visibilityOfElementLocated(locator)); + } + + /** + * Waits for element visibility with the provided timeout. + * + * @param locator the By locator to search for the element + * @param timeoutInSeconds the wait timeout in seconds + * @return the WebElement if visible before timeout, otherwise throws an exception + */ + protected WebElement waitForElementVisibility(final By locator, final int timeoutInSeconds) { + return getWait(timeoutInSeconds) + .until(ExpectedConditions.visibilityOfElementLocated(locator)); + } + + /** + * Waits for element invisibility with the default timeout. + * + * @param locator the By locator to search for the element + * @return the WebElement if invisible before timeout, false otherwise + */ + protected Boolean waitForElementInvisibility(final By locator) { + return getWait(timeoutInSeconds) + .until(ExpectedConditions.invisibilityOfElementLocated(locator)); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/AdminGeneralPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/AdminGeneralPage.java new file mode 100644 index 0000000000..2773c8c173 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/AdminGeneralPage.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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.UserManagementTab; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class AdminGeneralPage extends GeneralPageElements { + + private static UserManagementTab userManagementTab = new UserManagementTab(); + + public static UserManagementTab getUserManagementTab() { + return userManagementTab; + } + + public static void selectCategoryManagmetTab() throws Exception { + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.AdminPageTabs.CATEGORY_MANAGEMENT.getValue()); + } + + public static void selectUserManagmetTab() throws Exception { + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.AdminPageTabs.USER_MANAGEMENT.getValue()); + } + + public static List<WebElement> getServiceCategoriesList() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.SERVICE_CATEGORY_HEADER.getValue()); + GeneralUIUtils.waitForLoader(); + return GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.CategoryManagement.SERVICE_CATEGORY_LIST.getValue()); + } + + public static List<WebElement> getResourceCategoriesList() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_HEADER.getValue()); + GeneralUIUtils.waitForLoader(); + return GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_LIST.getValue()); + } + + public static void createNewServiceCategory(String name) throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.SERVICE_CATEGORY_HEADER.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "Creating service..."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.NEW_CATEGORY_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + defineNewResourceCategoryName(name); + GeneralPageElements.clickOKButton(); + GeneralUIUtils.waitForLoader(); + } + + public static void selectElementFromList(List<WebElement> list, String elementToSelect) throws Exception { + + for (WebElement webElement : list) { + if (webElement.getText().toLowerCase().equals(elementToSelect.toLowerCase())) { + webElement.click(); + } + } + + } + + + public static void addSubCategoryToResource(List<WebElement> resourceList, String parentResource, String subCategoryName) throws Exception { + + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_HEADER.getValue()); + selectElementFromList(resourceList, parentResource); + SetupCDTest.getExtendTest().log(Status.INFO, "Creating..."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.NEW_SUB_CATEGORY_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + defineNewResourceCategoryName(subCategoryName); + GeneralPageElements.clickOKButton(); + GeneralUIUtils.waitForLoader(); + + + } + + public static void createNewResourceCategory(String name) throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.RESOURCE_CATEGORY_HEADER.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, "Creating..."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CategoryManagement.NEW_CATEGORY_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + defineNewResourceCategoryName(name); + GeneralPageElements.clickOKButton(); + GeneralUIUtils.waitForLoader(); + + } + + public void insertPropertyDefaultValue(String value) { + WebElement propertyValue = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_VALUE.getValue()); + propertyValue.clear(); + propertyValue.sendKeys(value); + } + + private static void defineNewResourceCategoryName(String name) { + WebElement categoryNameTextbox = getCategoryName(); + categoryNameTextbox.clear(); + categoryNameTextbox.sendKeys(name); + } + + private static WebElement getCategoryName() { + return GeneralUIUtils.getWebElementByClassName(DataTestIdEnum.CategoryManagement.NEW_CATEGORY_NAME.getValue()); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ComponentLeftMenu.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ComponentLeftMenu.java new file mode 100644 index 0000000000..e8fb276ce4 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ComponentLeftMenu.java @@ -0,0 +1,25 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +public interface ComponentLeftMenu { + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/CompositionPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/CompositionPage.java new file mode 100644 index 0000000000..d74b7e4c6d --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/CompositionPage.java @@ -0,0 +1,234 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.LeftPanelCanvasItems; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.Select; +import org.testng.AssertJUnit; + +import java.util.List; + +public class CompositionPage extends GeneralPageElements { + + private CompositionPage() { + super(); + } + + public static UploadArtifactPopup artifactPopup() { + return new UploadArtifactPopup(true); + } + + public static void searchForElement(String elementName) { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + elementName + " in the left panel"); + WebElement searchField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.SEARCH_ASSET.getValue()); + searchField.clear(); + searchField.sendKeys(elementName); + GeneralUIUtils.ultimateWait(); + } + + public static void showDeploymentArtifactTab() throws Exception { + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.DEPLOYMENT_ARTIFACT_TAB); + } + + public static void showInformationsTab() throws Exception { + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.INFORMATION_TAB); + } + + public static void showPropertiesAndAttributesTab() throws Exception { + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.PROPERTIES_AND_ATTRIBUTES_TAB); + } + + public static List<WebElement> getProperties() { + return PropertiesPage.getElemenetsFromTable(); + } + + public static List<WebElement> getDeploymentArtifacts() { + return getAllAddedArtifacts(); + } + + public static List<WebElement> getAllAddedArtifacts() { + String dataTestsId = DataTestIdEnum.CompositionScreenEnum.ARTIFACTS_LIST.getValue(); + return GeneralUIUtils.getWebElementsListBy(By.xpath("//*[contains(@data-tests-id,'" + dataTestsId + "')]")); + } + + public static void moveToInputsScreen() throws Exception { + openPagesMenu(2); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.MENU_INPUTS.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public static void moveToPropertiesScreen() throws Exception { + openPagesMenu(2); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.MENU_PROPERTIES_ASSIGNMENT.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public static void moveToOnboardScreen() throws Exception { + openPagesMenu(0); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.MENU_ONBOARD.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public static void moveToHomeScreen() throws Exception { + openPagesMenu(0); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.MENU_HOME.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + private static void openPagesMenu(int counter) { + Actions actions = new Actions(GeneralUIUtils.getDriver()); + List<WebElement> triangleList = GeneralUIUtils.getWebElementsListByClassName(DataTestIdEnum.CompositionScreenEnum.MENU_TRIANGLE_DROPDOWN.getValue()); + WebElement pagesMenu = triangleList.get(counter); + actions.moveToElement(pagesMenu).perform(); + } + + public static void changeComponentVersion(CanvasManager canvasManager, CanvasElement element, String version) { + changeComponentVersion(canvasManager, element, version, false); + } + + public static void changeComponentVersion(CanvasManager canvasManager, CanvasElement element, String version, boolean isValidate) { + try { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Changing component version to %s", version)); + canvasManager.clickOnCanvaElement(element); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue()); + //GeneralUIUtils.ultimateWait(); + Select selectlist = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue())); + while (selectlist.getOptions().size() == 0) { + selectlist = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue())); + } + GeneralUIUtils.ultimateWait(); + selectlist.selectByValue(version); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickSomewhereOnPage(); + + // Validate Selection + if (isValidate) { + GeneralUIUtils.ultimateWait(); + canvasManager.clickOnCanvaElement(element); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating component version changed to %s", version)); + String actualSelectedValue = GeneralUIUtils.getWebElementBy(By.xpath(String.format("//select[@data-tests-id='%s']//option[@selected='selected']", DataTestIdEnum.CompositionScreenEnum.CHANGE_VERSION.getValue()))).getText(); + AssertJUnit.assertTrue(actualSelectedValue.equals(version)); + } + } catch (Exception e) { + throw e; + } + } + + public static void clickAddArtifactButton() throws Exception { + clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum.ADD_ARTIFACT); + GeneralUIUtils.getWebElementByClassName("sdc-add-artifact"); + } + + public static String getSelectedInstanceName() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText(); + } + + public static void showInformationArtifactTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.INFORMATION_ARTIFACTS); + } + + public static void showAPIArtifactTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.API); + } + + public static void showInformationTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.INFORMATION); + } + + public static void showCompositionTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.COMPOSITION); + } + + public static void showInputsTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.INPUTS); + } + + public static void showRequirementsAndCapabilitiesTab() throws Exception { + clickOnTab(DataTestIdEnum.CompositionScreenEnum.REQUIREMENTS_AND_CAPABILITIES); + } + + public static List<WebElement> getOpenTabTitle() throws Exception { + return GeneralUIUtils.getElementsByCSS("expand-collapse ng-transclude"); + } + + public static void clickOnTab(DataTestIdEnum.CompositionScreenEnum tabSelector) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", tabSelector.name())); + GeneralUIUtils.getElementsByCSS(tabSelector.getValue()).get(0).click(); + GeneralUIUtils.ultimateWait(); + } + + public static void clickOnTabTestID(DataTestIdEnum.CompositionScreenEnum tabSelector) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", tabSelector.name())); + GeneralUIUtils.getWebElementByTestID(tabSelector.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + + public static CanvasElement addElementToCanvasScreen(LeftPanelCanvasItems elementName, CanvasManager vfCanvasManager) throws Exception { + CompositionPage.searchForElement(elementName.name()); + return vfCanvasManager.createElementOnCanvas(elementName); + } + + public static CanvasElement addElementToCanvasScreen(String elementName, CanvasManager vfCanvasManager) throws Exception { + CompositionPage.searchForElement(elementName); + return vfCanvasManager.createElementOnCanvas(elementName); + } + + public static List<WebElement> getCompositionDeplymentArtifacts() { + return GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue()); + } + + public static WebElement getCustomizationUUID() throws Exception { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionScreenEnum.CUSTOMIZATION_UUID.getValue()); + } + + + public static List<WebElement> getCompositionEnvArtifacts() { + return GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ENV.getValue()); + } + + public static WebElement clickDownloadEnvArtifactComposition(String fileName) { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_ENV.getValue() + fileName); + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + fileName); + } + + public static void setSingleProperty(String propertyDataTestID, String propertyValue) { + WebElement findElement = GeneralUIUtils.getWebElementByTestID(propertyDataTestID); + findElement.click(); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(propertyValue); + PropertiesPage.getPropertyPopup().clickSave(); + GeneralUIUtils.ultimateWait(); + findElement = GeneralUIUtils.getWebElementByTestID("value_" + propertyDataTestID); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating property %s is set", propertyValue)); + AssertJUnit.assertTrue(findElement.getText().equals(propertyValue)); + GeneralUIUtils.ultimateWait(); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/DeploymentArtifactPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/DeploymentArtifactPage.java new file mode 100644 index 0000000000..eab4d3bcb3 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/DeploymentArtifactPage.java @@ -0,0 +1,312 @@ +/*-
+ * ============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.onap.sdc.frontend.ci.tests.pages;
+
+import com.aventstack.extentreports.Status;
+import org.apache.commons.lang.WordUtils;
+import org.onap.sdc.backend.ci.tests.datatypes.enums.ArtifactTypeEnum;
+import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo;
+import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum;
+import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions;
+import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest;
+import org.onap.sdc.frontend.ci.tests.utilities.FileHandling;
+import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils;
+import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebElement;
+import org.testng.collections.Lists;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+public class DeploymentArtifactPage extends GeneralPageElements {
+
+ protected DeploymentArtifactPage() {
+ super();
+ }
+
+ public static ResourceLeftMenu getLeftPanel() {
+ return new ResourceLeftMenu();
+ }
+
+ public static UploadArtifactPopup artifactPopup() {
+ return new UploadArtifactPopup();
+ }
+
+ protected static void addNewArtifact(ArtifactGroupTypeEnum artifactGroupType) {
+ switch (artifactGroupType) {
+ case DEPLOYMENT:
+ GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.ADD_DEPLOYMENT_ARTIFACT.getValue()).click();
+ break;
+ case INFORMATIONAL:
+ GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.ADD_INFORMATIONAL_ARTIFACT.getValue()).click();
+ break;
+ default:
+ break;
+ }
+ }
+
+ public static void clickAddNewArtifact() {
+ addNewArtifact(ArtifactGroupTypeEnum.DEPLOYMENT);
+ }
+
+ public static void clickAddAnotherArtifact() {
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.ADD_ANOTHER_ARTIFACT.getValue()).click();
+ }
+
+ public static void clickEditArtifact(String artifactLabel) {
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + artifactLabel).click();
+ }
+
+ public static void clickEditEnvArtifact(String artifactLabel) {
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactLabel).click();
+ }
+
+ public static void hoverArtifact(String artifactLabel) {
+ GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_NAME.getValue() + artifactLabel);
+ }
+
+ public static void clickDeleteArtifact(String artifactLabel) {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Deleting %s Artefact ", artifactLabel));
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + artifactLabel).click();
+ }
+
+ public static WebElement clickDownloadArtifact(String artifactLabel) {
+ WebElement downloadButton = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + artifactLabel);
+
+ return downloadButton;
+ }
+
+ public static void clickDownloadEnvArtifact(String envFileNameToDownload) {
+ ExtentTestActions.log(Status.INFO, String.format("Downloading the updated %s artifact for validate parameters with the response after the update...", envFileNameToDownload));
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + envFileNameToDownload);
+ ExtentTestActions.log(Status.INFO, String.format("%s Envartifact was downloaded successfully!", envFileNameToDownload));
+ }
+
+ public static void clickSaveEnvParameters() {
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.SAVE.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static void clickCloseEnvParameters() {
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.CANCEL_BUTTON.getValue()).click();
+ GeneralUIUtils.ultimateWait();
+ }
+
+ public static WebElement getAddOtherArtifactButton() {
+ return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.ADD_ANOTHER_ARTIFACT.getValue());
+ }
+
+ public static void clickOK() {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Artifact Page, Clicking OK");
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.OK.getValue()).click();
+ GeneralUIUtils.getWebElementBy(By.className("flex-container"));
+ GeneralUIUtils.waitForAngular();
+ }
+
+ public static String getArtifactDescription(String artifactLabel) throws Exception {
+ clickOnArtifactDescription(artifactLabel); // open artifact
+ WebElement artifactDescriptionElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.GET_DEPLOYMENT_ARTIFACT_DESCRIPTION.getValue());
+ String artifactDesc = artifactDescriptionElement.getAttribute("value");
+ closeArtifactDescription(artifactLabel); // close artifact
+ return artifactDesc;
+ }
+
+ public static void closeArtifactDescription(String artifactLabel) {
+ GeneralUIUtils.clickOnElementByTestId("popover-x-button");
+ }
+
+ public static WebElement clickOnArtifactDescription(String artifactLabel) throws Exception {
+ try {
+ WebElement artifact = GeneralUIUtils.getWebElementByTestID("descriptionIcon_" + artifactLabel);
+ artifact.click();
+ GeneralUIUtils.waitForLoader();
+ return artifact;
+ } catch (Exception e) {
+ throw new Exception("Artifact " + artifactLabel + "is not found");
+ }
+ }
+
+ public static boolean checkElementsCountInTable(int expectedElementsCount) {
+ return GeneralPageElements.checkElementsCountInTable(expectedElementsCount + 1);
+ }
+
+ public static String[] verifyArtifactsExistInTable(String filepath, String vnfFile) throws Exception {
+ String[] artifactNamesFromZipFile = FileHandling.getArtifactsFromZip(filepath, vnfFile);
+ return verifyArtifactsExistInTable(artifactNamesFromZipFile);
+ }
+
+ public static String[] verifyArtifactsExistInTable(String[] artifactNamesFromZipFile) throws Exception {
+ if (artifactNamesFromZipFile != null) {
+ checkArtifactsDisplayed(artifactNamesFromZipFile);
+ checkEnvArtifactsDisplayed();
+ }
+
+ return artifactNamesFromZipFile;
+ }
+
+ public static void checkArtifactsDisplayed(String[] artifactsFromZipFile) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the artifacts in the table");
+ List<String> artifactList = Lists.newArrayList(artifactsFromZipFile).stream().filter(p -> !p.contains(".env")).map(p -> getVisualArtifactName(p)).collect(Collectors.toList());
+ try {
+ List<WebElement> rows = GeneralUIUtils.getWebElementsListByContainsClassName("datatable-body-row");
+ for (WebElement r : rows) {
+ String artifactDisplayed = r.getAttribute("textContent").trim();
+ if (artifactList.contains(artifactDisplayed)) {
+ artifactList.remove(artifactDisplayed);
+ } else if (artifactDisplayed.toLowerCase().contains("license")) {
+ artifactList.add(artifactDisplayed);
+ }
+ }
+ checkLicenseArtifactsDisplayed(artifactList);
+ } catch (Exception e) {
+ throw new Exception("Table problem");
+ }
+
+
+ if (!artifactList.isEmpty()) {
+ throw new Exception(String.format("missing the following artifact(s) : %s", artifactList.toString()));
+ }
+ }
+
+ public static void checkEnvArtifactsDisplayed() throws Exception {
+ List<WebElement> envRows;
+ List<WebElement> heatRows;
+ List<WebElement> heatNetRows;
+ List<WebElement> heatVolRows;
+ int envArtifactsSize = 0;
+
+ SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the HEAT_ENV artifacts in the table");
+
+ try {
+ envRows = GeneralUIUtils.getElementsByCSS("div div[data-tests-id='HEAT_ENV']");
+
+ heatRows = GeneralUIUtils.getElementsByCSS("div div[tooltip-content='HEAT']");
+ heatNetRows = GeneralUIUtils.getElementsByCSS("div div[tooltip-content='HEAT_NET']");
+ heatVolRows = GeneralUIUtils.getElementsByCSS("div div[tooltip-content='HEAT_VOL']");
+
+ envArtifactsSize = heatRows.size() + heatNetRows.size() + heatVolRows.size();
+ } catch (Exception e) {
+ throw new Exception("Table problem");
+ }
+
+ if (envArtifactsSize != envRows.size()) {
+ throw new Exception(String.format("some env artifacts are missing... there is %s instead of %s", envRows.size(), envArtifactsSize));
+ }
+
+ }
+
+ public static void checkLicenseArtifactsDisplayed(List<String> rowsFromTable) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the license artifacts in the table");
+ String vfLicense = getPreparedLicense(ArtifactTypeEnum.VF_LICENSE.getType());
+ String[] split = vfLicense.split(" ");
+ vfLicense = vfLicense.replaceAll(split[0], split[0].toUpperCase());
+ if (rowsFromTable.contains(vfLicense)) {
+ rowsFromTable.remove(vfLicense);
+ }
+
+ String vendorLicense = getPreparedLicense(ArtifactTypeEnum.VENDOR_LICENSE.getType());
+ if (rowsFromTable.contains(vendorLicense)) {
+ rowsFromTable.remove(vendorLicense);
+ }
+
+ }
+
+ public static String getPreparedLicense(String license) {
+ return WordUtils.capitalizeFully(license.replaceAll("_", " "));
+ }
+
+
+ private static String getVisualArtifactName(String artifactName) {
+ if (artifactName.contains(".")) {
+ return artifactName.substring(0, artifactName.lastIndexOf("."));
+ }
+ return artifactName;
+ }
+
+ public static void updateDescription(String newDescription, ArtifactInfo artefact) throws Exception {
+ UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true);
+ DeploymentArtifactPage.clickEditArtifact(artefact.getArtifactLabel());
+ artifactPopup.insertDescription(newDescription);
+ artifactPopup.clickDoneButton();
+ }
+
+ public static List<String> getDeploymentArtifactsNamesWorkSpace() {
+ return GeneralUIUtils.getWebElementListText(GeneralUIUtils.getWebElementsListByContainTestID(DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue()));
+ }
+
+ //Get Artifact Type by Artifact Name.
+ public static String getArtifactType(String artifactName) {
+ return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + artifactName).getText();
+ }
+
+ public static List<String> getHeatParametersInUI(String dataTestId) {
+ List<WebElement> elements;
+ List<String> Names = new ArrayList<>();
+ elements = GeneralUIUtils.getWebElementsListByContainTestID(dataTestId);
+ for (WebElement webElement : elements) {
+ String attributevalue = webElement.getAttribute("data-tests-id");
+ Names.add(attributevalue.replace("heatParameterName_", ""));
+ }
+ return Names;
+ }
+
+ public static void searchBoxEnv(String parameterName) {
+ GeneralUIUtils.getWebElementByContainsClassName("w-sdc-env-search-input").sendKeys(parameterName);
+ }
+
+ public static void clearSearchBoxEnv() {
+ GeneralUIUtils.getWebElementByContainsClassName("w-sdc-env-search-input").clear();
+ }
+
+ public static void editHeatParamValue(String paramName, String value) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + paramName + " parameter on Heat Params modal screen");
+ WebElement valueTextbox = GeneralUIUtils.getWebElementByTestID(paramName);
+
+ clickOnHeatParam(paramName);
+ valueTextbox.clear();
+ SetupCDTest.getExtendTest().log(Status.INFO, "Editing " + paramName + " value on Heat Params modal screen");
+ valueTextbox.sendKeys(value);
+ GeneralUIUtils.ultimateWait();
+
+ }
+
+ public static void clickOnDeleteHeatParamValue(String paramName) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + paramName + " parameter on Properties screen");
+ String value = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.EnvParameterView.ENV_CURRENT_VALUE.getValue() + paramName).getAttribute("value");
+ if (value != null) {
+ GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DELETE_PARAMETER_OF_ARTIFACT.getValue() + paramName);
+ GeneralUIUtils.ultimateWait();
+ SetupCDTest.getExtendTest().log(Status.INFO, "Value of " + paramName + " is deleted");
+ }
+ SetupCDTest.getExtendTest().log(Status.INFO, "Value of " + paramName + " is empty and cannot be deleted");
+ }
+
+ public static void clickOnHeatParam(String paramName) throws Exception {
+
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component in Properties", paramName));
+ GeneralUIUtils.clickOnElementByTestId(paramName);
+ GeneralUIUtils.ultimateWait();
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue());
+ }
+
+}
diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/DeploymentPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/DeploymentPage.java new file mode 100644 index 0000000000..4aa8f9db64 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/DeploymentPage.java @@ -0,0 +1,234 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.DeploymentScreen; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DeploymentPage { + + public DeploymentPage() { + super(); + } + + public static List<WebElement> getGroupMembersList(String instanceName) { + List<WebElement> propertyRows = null; + clickOnModuleName(instanceName); + propertyRows = getVisibleMembers(); + return propertyRows; + } + + public static void clickOnModuleName(String instanceName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", instanceName)); + GeneralUIUtils.clickOnElementByText(instanceName); + GeneralUIUtils.ultimateWait(); + } + + public static List<WebElement> getVisibleMembers() { + List<WebElement> instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='hierarchy-module-member-list']")); + for (WebElement instance : instancesFromTable) { + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")) { + return instance.findElements(By.cssSelector("div[class^='expand-collapse-sub-title']")); + } + } + return null; + } + + public static void clickOnProperties() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Properties button")); + GeneralUIUtils.clickOnElementByCSS(DataTestIdEnum.DeploymentScreen.BUTTON_PROPERTIES.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static void clickOnArtifacts() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Artifacts button")); + GeneralUIUtils.clickOnElementByCSS(DataTestIdEnum.DeploymentScreen.BUTTON_ARTIFACTS.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static void clickOnSaveButton() { + clickInDeployment(DataTestIdEnum.DeploymentScreen.SAVE); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("popover-inner")); + } + + public static void clickOnCancelButton() { + clickInDeployment(DataTestIdEnum.DeploymentScreen.CANCEL); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("popover-inner")); + } + + public static void clickOnXIcon() { + clickInDeployment(DataTestIdEnum.DeploymentScreen.X_BUTTON); + GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("popover-inner")); + } + + public static void clickOnEditIcon() { + clickInDeployment(DataTestIdEnum.DeploymentScreen.PENCIL_ICON); + } + + public static void clickOnProperty(WebElement property) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s propertie ...", property.getText())); + property.click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.POPUP_FORM.getValue()); + } + + private static void clickInDeployment(DataTestIdEnum.DeploymentScreen element) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s ...", element.getValue())); + GeneralUIUtils.clickOnElementByTestId(element.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public static List<WebElement> getPropertyNames() throws Exception { + clickOnProperties(); + return GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.PROPERTY_NAMES.getValue()); + } + + public static List<WebElement> getArtifactNames() throws Exception { + clickOnArtifacts(); + return GeneralUIUtils.getInputElements(DataTestIdEnum.DeploymentScreen.ARTIFACT_NAME.getValue()); + } + + public static String updateModuleName(String currentModuleName, String newModuleName) throws Exception { + GeneralUIUtils.ultimateWait(); + ResourceUIUtils.clickOnElementByText(currentModuleName, null); + GeneralUIUtils.ultimateWait(); + clickOnEditIcon(); + WebElement moduleNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.NAME_INPUT.getValue()); + String oldModuleName = moduleNameField.getAttribute("value"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating %s module name ...", currentModuleName)); + moduleNameField.clear(); + GeneralUIUtils.ultimateWait(); + moduleNameField.sendKeys(newModuleName); + GeneralUIUtils.ultimateWait(); + clickOnSaveButton(); + String newReconstructedModuleName = reconstructModuleName(currentModuleName.split("\\.\\."), newModuleName); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Name of element instance changed from %s to %s", currentModuleName, newReconstructedModuleName)); + return oldModuleName; + } + + public static String reconstructModuleName(String[] splittedName, String middleName) { + int i = 0; + StringBuilder builder = new StringBuilder(); + for (String s : splittedName) { + if (i == 1) { + builder.append(middleName); + } else { + builder.append(s); + } + if (i < 2) { + builder.append(".."); + } + i++; + } + return builder.toString(); + } + + public static List<WebElement> getVisibleModulesService() { + List<WebElement> instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='hierarchy-modules-list']")); + for (WebElement instance : instancesFromTable) { + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")) { + return instance.findElements(By.cssSelector("span[class^='expand-collapse-title-text']")); + } + } + return null; + } + + public static List<WebElement> getInstanceModulesList(String instanceName) { + List<WebElement> propertyRows = null; + ResourceUIUtils.clickOnElementByText(instanceName, null); + GeneralUIUtils.ultimateWait(); + propertyRows = getVisibleModulesService(); + return propertyRows; + } + + public static String getGroupVersion() throws Exception { + return GeneralUIUtils.getElementsByCSS("div[data-tests-id='selected-module-version']").get(0).getText(); + } + + public static String getModuleID() throws Exception { + return GeneralUIUtils.getElementsByCSS("div[data-tests-id='selected-module-group-uuid'] span[class^='small-font']").get(0).getText(); + } + + public static Map<String, HashMap<String, String>> collectMetaDataFromUI() throws Exception { + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + Map<String, HashMap<String, String>> deploymentViewMetaData = new HashMap<String, HashMap<String, String>>(); + List<WebElement> moduleRowsFromTable = GeneralUIUtils.getElementsByCSS("span[class^='expand-collapse-title-text']"); + for (WebElement moduleRow : moduleRowsFromTable) { + HashMap<String, String> tempGroupMap = new HashMap<String, String>(); + String moduleRowText = moduleRow.getText(); + GeneralUIUtils.clickOnElementByText(moduleRowText); + tempGroupMap.put("moduleID", getModuleID()); + tempGroupMap.put("version", DeploymentPage.getGroupVersion().split(":")[1].trim()); + deploymentViewMetaData.put(moduleRowText.split("\\.\\.")[1], tempGroupMap); + GeneralUIUtils.clickOnElementByText(moduleRowText); + } + return deploymentViewMetaData; + } + + public static void updateAndCancel(String newModuleName, DataTestIdEnum.DeploymentScreen buttonToClick) { + WebElement moduleNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.NAME_INPUT.getValue()); + String oldModuleName = moduleNameField.getAttribute("value"); + moduleNameField.clear(); + GeneralUIUtils.ultimateWait(); + moduleNameField.sendKeys(newModuleName); + GeneralUIUtils.ultimateWait(); + if (buttonToClick.equals(DataTestIdEnum.DeploymentScreen.X_BUTTON)) { + clickOnXIcon(); + } else { + clickOnCancelButton(); + } + } + + public static String getPropertyValueFromPropertiesList(String property) throws InterruptedException { + List<WebElement> propertyDataElements = GeneralUIUtils.getElementsByCSS("div[class^='list-item property-data']"); + for (WebElement propertyDataElement : propertyDataElements) { + WebElement propertyNameElement = GeneralUIUtils.getElementfromElementByCSS(propertyDataElement, DeploymentScreen.PROPERTY_NAMES.getValue()); + if (propertyNameElement.getText().equals(property)) { + WebElement propertyValueElement = GeneralUIUtils.getElementfromElementByCSS(propertyDataElement, String.format("div[data-tests-id='%s']", DeploymentScreen.PROPERTY_SCHEMA_TYPE.getValue())); + return propertyValueElement.getText().trim().split(":")[1].trim(); + } + } + return null; + } + + public static List<WebElement> getPropertyErrorValidationMessdge() throws Exception { + List<WebElement> propertyErrorElements = GeneralUIUtils.getElementsByCSS("div[class='input-error'] span[class='ng-scope']"); + return propertyErrorElements; + } + + public static boolean isPropertySaveButtonDisabled() { + WebElement saveButtonElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.SAVE.getValue()); + return GeneralUIUtils.isElementDisabled(saveButtonElement); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/GeneralPageElements.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/GeneralPageElements.java new file mode 100644 index 0000000000..2397815c98 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/GeneralPageElements.java @@ -0,0 +1,271 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.CatalogUIUtilitis; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriverException; +import org.openqa.selenium.WebElement; + +import java.util.List; +import java.util.function.Supplier; + +public class GeneralPageElements { + + private static final int WAIT_FOR_ELEMENT_TIME_OUT = 60; + private static final int WAIT_FOR_ELEMENT_TIME_OUT_DIVIDER = 10; + + protected GeneralPageElements() { + + } + + public static ResourceLeftMenu getLeftMenu() { + return new ResourceLeftMenu(); + } + + public static void clickOKButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the OK button"); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + } + + public static void clickCreateButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the CREATE/UPDATE button."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + ExtentTestActions.log(Status.INFO, "Succeeded."); + } + + public static void clickCreateButton(int timeout) { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the CREATE/UPDATE button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue(), timeout); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + + public static void clickCreateUpdateButton(int timeout) { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the CREATE/UPDATE button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue(), timeout); + GeneralUIUtils.ultimateWait(); + } + + public static void clickUpdateButton() { + clickCreateButton(); + } + + public static void clickCheckinButton(String componentName) { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the CHECKIN button"); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.ACCEPT_TESTING_MESSAGE.getValue()).sendKeys("Checkin " + componentName); + clickOKButton(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static void clickSubmitForTestingButton(String componentName) { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the submitting for testing button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.SUBMIT_FOR_TESTING_BUTTON.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.SUMBIT_FOR_TESTING_MESSAGE.getValue()).sendKeys("Submit for testing " + componentName); + GeneralUIUtils.ultimateWait(); + clickOKButton(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue(), WAIT_FOR_ELEMENT_TIME_OUT); + GeneralUIUtils.ultimateWait(); + } + + public static void clickSubmitForTestingButtonErrorCase(String componentName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on the submitting for testing button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.SUBMIT_FOR_TESTING_BUTTON.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.SUMBIT_FOR_TESTING_MESSAGE.getValue()).sendKeys("Submit for testing " + componentName); + GeneralUIUtils.ultimateWait(); + clickOKButton(); + clickOKButton(); + } + + public static void restoreComponentFromArchivedCatalog(String componentName) throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CatalogSwitchButtons.CATALOG_SWITCH_BUTTON.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.CatalogSwitchButtons.CATALOG_ARCHIVE.getValue()); + GeneralUIUtils.findComponentAndClick(componentName); + clickRestoreButton(componentName); + } + + public static void restoreComponentFromElementPage(String componentName) throws Exception { + clickRestoreButton(componentName); + } + + private static void clickRestoreButton(String componentName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to restore component: %s", componentName)); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.RESTORE_BUTTON.getValue()); + } + + public static void clickArchivedButtonFromCatalog(String componentName) throws Exception { + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(componentName); + clickArchiveButton(componentName); + } + + public static void archiveComponentFromElementPage(String componentName) throws Exception { + clickArchiveButton(componentName); + } + + private static void clickArchiveButton(String componentName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Going to archive component: %s", componentName)); + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.GeneralElementsEnum.ARCHIVE_BUTTON.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.ARCHIVE_BUTTON.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Component %s archived successfully", componentName)); + } + + //TODO should implement real code + public static void clickCertifyButton(String componentName) throws Exception { + try { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on certify button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.LifeCyleChangeButtons.CERTIFY.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) + .sendKeys("resource " + componentName + " certified successfully"); + clickOKButton(); + GeneralUIUtils.ultimateWait(); + HomePage.navigateToHomePage(); + GeneralUIUtils.ultimateWait(); + HomePage.navigateToHomePage(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue(), GeneralUIUtils.getTimeOut() / WAIT_FOR_ELEMENT_TIME_OUT_DIVIDER); + GeneralUIUtils.ultimateWait(); + } catch (Exception e) { + throw new Exception("Certification of " + componentName + " failed"); + } + } + + public static void clickCertifyButtonNoUpgradePopupDismiss(String componentName) throws Exception { + try { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on certify button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.LifeCyleChangeButtons.CERTIFY.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) + .sendKeys("resource " + componentName + " certified successfully"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + } catch (Exception e) { + throw new Exception("Certification of " + componentName + " failed"); + } + } + + public static void clickCertifyButtonNoUpgradePopupDismissErrorCase(String componentName) throws Exception { + try { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on certify button"); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.LifeCyleChangeButtons.CERTIFY.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) + .sendKeys("resource " + componentName + " certified successfully"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.OK.getValue()).click(); + clickOKButton(); + } catch (Exception e) { + throw new Exception("Certification of " + componentName + " failed"); + } + } + + public static void clickUpgradeServicesCloseButton() { + WebElement closeButton = null; + try { + closeButton = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.UPGRADE_SERVICES_CANCEL.getValue(), GeneralUIUtils.getTimeOut() / WAIT_FOR_ELEMENT_TIME_OUT_DIVIDER); + UpgradeServicesPopup.setUpgradePopupShown(true); + SetupCDTest.getExtendTest().log(Status.INFO, "Closing Update Services popup with X button ..."); + closeButton.click(); + } catch (WebDriverException e) { + // regular flow + UpgradeServicesPopup.setUpgradePopupShown(false); + SetupCDTest.getExtendTest().log(Status.INFO, "Update Services popup is not shown, continuing ..."); + } + } + + public static void clickCheckoutButton() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on CHECKOUT button ..."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CHECKOUT_BUTTON.getValue()); + GeneralUIUtils.ultimateWait(); + } + + + public static void clickDeleteVersionButton() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on DELETE VERSION button ..."); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.DELETE_VERSION_BUTTON.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.OK.getValue()); + } + + public static void clickRevertButton() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on REVERT button ..."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.REVERT_BUTTON.getValue()); + } + + public static String getLifeCycleState() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()).getText(); + } + + public static String getWebElementTextByTestId(String dataTestIdEnumValue) { + return GeneralUIUtils.getWebElementByTestID(dataTestIdEnumValue).getText(); + } + + public static void selectVersion(String version) { + GeneralUIUtils.getSelectList(version, DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()); + GeneralUIUtils.ultimateWait(); + } + + public static List<WebElement> getElementsFromTable() { + GeneralUIUtils.ultimateWait(); + return GeneralUIUtils.getElementsByLocator(By.className("datatable-body")); + } + + public static boolean checkElementsCountInTable(int expectedElementsCount) { + return checkElementsCountInTable(expectedElementsCount, () -> getElementsFromTable()); + } + + + public static void clickTrashButtonAndConfirm() throws InterruptedException { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on TRASH button ..."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.DELETE_VERSION_BUTTON.getValue()); + clickOKButton(); + } + + public static void clickBrowseButton() throws InterruptedException { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Browse button ..."); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.ModalItems.BROWSE_BUTTON.getValue()); + } + + public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier<List<WebElement>> func) { + SetupCDTest.getExtendTest().log(Status.INFO, "Checking the number of elements in the table; should be " + (expectedElementsCount - 1)); + GeneralUIUtils.ultimateWait(); + return true; + } + + public static void clickDeleteFile() throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on delete file X-button ..."); + GeneralUIUtils.clickOnAreaJS(GeneralUIUtils.getWebElementBy(By.cssSelector("div[class='i-sdc-form-file-upload-x-btn']"))); + GeneralUIUtils.ultimateWait(); + } + + public static void clickOnHomeButton() { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/GovernorOperationPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/GovernorOperationPage.java new file mode 100644 index 0000000000..02fdff7cdb --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/GovernorOperationPage.java @@ -0,0 +1,63 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public class GovernorOperationPage { + + private static final Logger LOGGER = LoggerFactory.getLogger(GovernorOperationPage.class); + + private GovernorOperationPage() { + super(); + } + + public static void approveService(final String serviceName) { + SetupCDTest.getExtendTest() + .log(Status.INFO, String.format("Approving the distribution of the service '%s'", serviceName)); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.APPROVE_MESSAGE.getValue()) + .sendKeys("service " + serviceName + " tested successfully"); + GeneralPageElements.clickOKButton(); + final String distributionApprovedMsg = String.format("The distribution of the service '%s' was approved", serviceName); + try { + ExtentTestActions + .addScreenshot(Status.INFO, + String.format("governor-distribution-approved-%s", serviceName), + distributionApprovedMsg + ); + } catch (final IOException e) { + LOGGER.error("Could not take screenshot of governor distribution approval", e); + SetupCDTest.getExtendTest().log(Status.INFO, distributionApprovedMsg); + } + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/HeatParamNameBuilder.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/HeatParamNameBuilder.java new file mode 100644 index 0000000000..75ddb44d97 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/HeatParamNameBuilder.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; + +public class HeatParamNameBuilder { + private static final String CURRENT_VAL = DataTestIdEnum.EnvParameterView.ENV_CURRENT_VALUE.getValue(); + private static final String DEFAULT_VAL = DataTestIdEnum.EnvParameterView.ENV_DEFAULT_VALUE.getValue(); + + private HeatParamNameBuilder() {} + + public static String buildCurrentHeatParamValue(String paramName) { + return new StringBuilder().append(CURRENT_VAL).append(paramName).toString(); + } + + public static String buildDefaultHeatParamValue(String paramName) { + return new StringBuilder().append(DEFAULT_VAL).append(paramName).toString(); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/HomePage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/HomePage.java new file mode 100644 index 0000000000..4f270cf751 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/HomePage.java @@ -0,0 +1,231 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.exception.HomePageRuntimeException; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.utilities.DownloadManager; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.List; +import java.util.UUID; + +import static org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest.getExtendTest; +import static org.onap.sdc.frontend.ci.tests.pages.HomePage.PageElement.REPOSITORY_ICON; + +public class HomePage { + + private static final Logger LOGGER = LoggerFactory.getLogger(HomePage.class); + + private static final int WAIT_FOR_ELEMENT_TIME_OUT = 30; + private static final int WAIT_FOR_LOADER_TIME_OUT = 600; + + private HomePage() { + + } + + public static void showVspRepository() { + GeneralUIUtils.waitForElementInVisibilityBy(By.className("ui-notification"), WAIT_FOR_ELEMENT_TIME_OUT); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.MainMenuButtons.REPOSITORY_ICON.getValue()); + } + + public static boolean searchForVSP(String vspName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ImportVfRepository.SEARCH.getValue()).clear(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ImportVfRepository.SEARCH.getValue()).sendKeys(vspName); + GeneralUIUtils.ultimateWait(); + return true; + } + + public static void importVSP(String vspName) { + HomePage.showVspRepository(); + boolean vspFound = HomePage.searchForVSP(vspName); + if (vspFound) { + List<WebElement> elementsFromTable = GeneralPageElements.getElementsFromTable(); + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), WAIT_FOR_ELEMENT_TIME_OUT); + WebElement findElement = wait.until(ExpectedConditions.visibilityOf(elementsFromTable.get(1))); + findElement.click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(WAIT_FOR_LOADER_TIME_OUT); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + } + + public static boolean navigateToHomePage() { + try { + LOGGER.debug("Searching for repository icon"); + final WebElement repositoryIcon = GeneralUIUtils.getInputElement(REPOSITORY_ICON.getTestId()); + if (repositoryIcon != null) { + return true; + } + GeneralUIUtils.ultimateWait(); + final List<WebElement> homeButtons = GeneralUIUtils + .getElementsByLocator(By.xpath("//a[contains(.,'HOME')]")); + if (!homeButtons.isEmpty()) { + homeButtons.stream().filter(WebElement::isDisplayed).findFirst().ifPresent(webElement -> { + webElement.click(); + LOGGER.debug("Clicked on home button"); + }); + } + + GeneralUIUtils.closeErrorMessage(); + WebElement homeButton = GeneralUIUtils + .getInputElement(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue()); + return homeButton != null && homeButton.isDisplayed(); + + } catch (final Exception e) { + final String msg = "Could not click on home button"; + getExtendTest() + .log(Status.WARNING, msg); + LOGGER.warn(msg, e); + return false; + } + } + + public static File downloadVspCsarToDefaultDirectory(String vspName) throws Exception { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtonsFromInsideFrame.HOME_BUTTON.getValue()).click(); + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, ""); + return FileHandling.getLastModifiedFileNameFromDir(); + } + + public static void findComponentAndClick(final String resourceName) { + findComponent(resourceName); + clickComponent(resourceName); + } + + public static void findComponent(final String resourceName) { + LOGGER.debug("Searching for component '{}'", resourceName); + getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in home tab"); + clearSearchResults(getSearchInput()); + searchForComponent(resourceName); + } + + private static WebElement getSearchInput() { + WebElement searchTextbox; + try { + searchTextbox = TopSearchComponent.getComponentInput(); + LOGGER.debug("Search textbox '{}' selected", TopSearchComponent.SEARCH_INPUT_TEST_ID); + } catch (final Exception e) { + final String errorMsg = "Top Search bar was not visible"; + getExtendTest().log(Status.ERROR, errorMsg); + throw new HomePageRuntimeException(errorMsg, e); + } + return searchTextbox; + } + + private static void clearSearchResults(final WebElement searchTextbox) { + try { + LOGGER.debug("Clearing search results before searching"); + TopSearchComponent.replaceSearchValue(searchTextbox, UUID.randomUUID().toString()); + MainRightContainer.isEmptyResult(); + } catch (final Exception e) { + final String errorMsg = "Could not clean up the search result"; + getExtendTest().log(Status.ERROR, errorMsg); + throw new HomePageRuntimeException(errorMsg, e); + } + } + + private static void searchForComponent(final String resourceName) { + try { + LOGGER.debug("Searching for '{}'", resourceName); + TopSearchComponent.replaceSearchValue(resourceName); + MainRightContainer.isResultVisible(resourceName); + } catch (final Exception e) { + final String errorMsg = String.format("Could not find the component '%s' after search", resourceName); + getExtendTest().log(Status.ERROR, errorMsg); + throw new HomePageRuntimeException(errorMsg, e); + } + } + + public static void clickComponent(final String resourceName) { + LOGGER.debug("Clicking on the component " + resourceName); + try { + getExtendTest() + .log(Status.INFO, String.format("Clicking on the '%s' component from home tab", resourceName)); + GeneralUIUtils.clickOnElementByTestId(resourceName); + } catch (final Exception e) { + final String errorMsg = String.format("Could not click on home tab component '%s' ", resourceName); + getExtendTest().log(Status.ERROR, e.getMessage()); + throw new HomePageRuntimeException(errorMsg, e); + } + final String datetimeString = + new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss.SSS").format(Calendar.getInstance().getTime()); + try { + ExtentTestActions + .addScreenshot(Status.INFO, + String.format("after-click-resource-%s-%s", resourceName, datetimeString), + String.format("Clicked on resource '%s'", resourceName) + ); + } catch (final IOException e) { + LOGGER.warn("Could take screenshot after resource {} click", resourceName, e); + } + try { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } catch (final Exception e) { + final String errorMsg = String.format("Expecting to be inside component '%s' screen", resourceName); + getExtendTest().log(Status.ERROR, e.getMessage()); + throw new HomePageRuntimeException(errorMsg, e); + } + } + + public static void waitForElement(PageElement homePageElement) { + final String cssClass = homePageElement.getCssClass(); + LOGGER.debug("Waiting for{} visibility", cssClass); + GeneralUIUtils.getWebElementByClassName(cssClass); + LOGGER.debug("{} is visible", cssClass); + } + + public enum PageElement { + COMPONENT_PANEL("w-sdc-main-right-container", null), + REPOSITORY_ICON(null, "repository-icon"); + + private final String cssClass; + private final String testId; + + PageElement(String cssClass, String testId) { + this.cssClass = cssClass; + this.testId = testId; + } + + public String getCssClass() { + return cssClass; + } + + public String getTestId() { + return testId; + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/IconPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/IconPage.java new file mode 100644 index 0000000000..99d2460f59 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/IconPage.java @@ -0,0 +1,51 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +public class IconPage extends GeneralPageElements { + + private IconPage() { + super(); + } + + public static void clickOnIcon(ResourceCategoryEnum iconName) { + GeneralUIUtils.getWebElementByTestID(iconStringBuilder(iconName) + DataTestIdEnum.ServiceMetadataEnum.ICON.getValue()) + .click(); + } + + private static String iconStringBuilder(ResourceCategoryEnum icon) { + String iconName = icon.getSubCategory(); + String[] splitedIconName = iconName.split(" "); + splitedIconName[0] = splitedIconName[0].toLowerCase(); + + StringBuilder sb = new StringBuilder(); + for (String word : splitedIconName) { + sb.append(word); + } + + return sb.toString(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/InformationalArtifactPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/InformationalArtifactPage.java new file mode 100644 index 0000000000..c299f54791 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/InformationalArtifactPage.java @@ -0,0 +1,72 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class InformationalArtifactPage extends DeploymentArtifactPage { + + private InformationalArtifactPage() { + super(); + } + + public static void clickAddNewArtifact() { + addNewArtifact(ArtifactGroupTypeEnum.INFORMATIONAL); + } + + public static String getArtifactDescription(String artifactLabel) throws Exception { + InformationalArtifactPage.clickOnArtifact(artifactLabel); + String artifactDesc = GeneralUIUtils.getWebElementByTestID( + artifactLabel + DataTestIdEnum.ArtifactPageEnum.GET_INFORMATIONAL_ARTIFACT_DESCRIPTION.getValue()) + .getText(); + InformationalArtifactPage.clickOnArtifact(artifactLabel); // close artifact + return artifactDesc; + } + + public static List<WebElement> getElemenetsFromTable() { + return GeneralUIUtils.getWebElementsListByTestID("InformationalArtifactRow"); + } + + public static WebElement clickOnArtifact(String artifactLabel) throws Exception { + try { + WebElement artifact = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel); + artifact.click(); + GeneralUIUtils.waitForLoader(); + return artifact; + } catch (Exception e) { + throw new Exception("Artifact " + artifactLabel + "is not found"); + } + } + + + public static void clickDeleteArtifact(String artifactLabel) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Deleting %s Artefact ", artifactLabel)); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + artifactLabel).click(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/InputsPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/InputsPage.java new file mode 100644 index 0000000000..2fbe3ac454 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/InputsPage.java @@ -0,0 +1,151 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.InputsScreenService; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.TestException; + +import java.util.List; +import java.util.stream.Collectors; + +public class InputsPage extends GeneralPageElements { + + private InputsPage() { + super(); + } + + public static List<WebElement> getInstancePropertiesList(String instanceName) { + List<WebElement> propertyRows = null; + GeneralUIUtils.clickOnElementByText(instanceName); + GeneralUIUtils.ultimateWait(); + propertyRows = getVisibleProperites(); + return propertyRows; + } + + static List<WebElement> getVisibleProperites() { + List<WebElement> instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='vf-instance-list']")); + for (WebElement instance : instancesFromTable) { + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")) { + return instance.findElements(By.className("property-row")); + } + } + return null; + } + + public static void addInputToService(String VFInstanceName, String propertyName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding property %s from VF instance %s to Service", propertyName, VFInstanceName)); + List<WebElement> instaceInputs = getInstanceInputsList(VFInstanceName); + for (WebElement instancInput : instaceInputs) { + String actualPropertyName = instancInput.findElement(By.className("title-text")).getText(); + if (actualPropertyName.equals(propertyName) && clickOnVFInputCheckbox(instancInput)) { + clickOnAddInputButton(); + } + } + } + + public static List<WebElement> getInstanceInputsList(String instanceName) { + List<WebElement> inputRows = null; + GeneralUIUtils.clickOnElementByText(instanceName); + GeneralUIUtils.ultimateWait(); + inputRows = getVisibleInputs(inputRows); + return inputRows; + } + + public static List<WebElement> getVisibleInputs(List<WebElement> inputRows) { + List<WebElement> instancesFromTable = GeneralUIUtils.getDriver().findElements(By.cssSelector("div[class^='vf-instance-list']")); + for (WebElement instance : instancesFromTable) { + Object parentAttributes = GeneralUIUtils.getAllElementAttributes(instance); + if (!parentAttributes.toString().contains("hidden")) { + inputRows = instance.findElements(By.className("input-row")); + break; + } + } + return inputRows; + } + + public static void clickOnAddInputButton() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Add Input aka Greater than symbol button")); + GeneralUIUtils.clickOnElementByTestId(InputsScreenService.ADD_SELECTED_INPUTS_BTN.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public static boolean clickOnVFInputCheckbox(WebElement instancInput) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on VF instance input checkbox")); + instancInput.findElement(By.className("tlv-checkbox-label")).click(); + GeneralUIUtils.ultimateWait(); + return instancInput.findElement(By.className("tlv-checkbox-i")).getAttribute("class").contains("ng-not-empty"); + } + + public static WebElement getServiceInput(String VFInstanceName, String propertyName) throws Exception { + String expectedInputName = String.format("%s_%s", VFInstanceName.replace(" ", "").toLowerCase(), propertyName); + List<WebElement> inputsFromTable = GeneralUIUtils.getElementsByCSS(InputsScreenService.SERVICE_INPUT_ROW.getValue()); + for (WebElement inputFromTable : inputsFromTable) { + String actualInputName = inputFromTable.findElement(By.className("title-text")).getText(); + if (actualInputName.equals(expectedInputName)) { + return inputFromTable; + } + } + throw new TestException(String.format("%s input don't exist", expectedInputName)); + } + + public static void deleteServiceInput(String VFInstanceName, String propertyName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Deleting property %s in VF instance %s ", propertyName, VFInstanceName)); + WebElement serviceInput = getServiceInput(VFInstanceName, propertyName); + serviceInput.findElement(By.cssSelector(InputsScreenService.DELETE_INPUT_BTN.getValue())).click(); + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on OK button ")); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.GeneralElementsEnum.OK.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public static List<String> getVFCInstancesNamesFromTable() throws Exception { + WebElement inputsTable = getInputsTable("VFC "); + return inputsTable.findElements(By.cssSelector("span[class^='title-text']")).stream(). + map(e -> e.getText()). + collect(Collectors.toList()); + } + + public static WebElement getInputsTable(String tableName) throws Exception { + List<WebElement> tableElements = GeneralUIUtils.getElementsByCSS("div.table"); + for (WebElement tableElement : tableElements) { + String tableTitle = GeneralUIUtils.getElementfromElementByCSS(tableElement, "div.table-header").getText(); + if (tableTitle.contains(tableName)) { + return tableElement; + } + } + throw new TestException(String.format("Can't find %s table", tableName)); + } + + public static void clickOnProperty(String propertyName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on property %s ", propertyName)); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.InputsScreenService.RESOURCE_INSTANCE_PROPERTY_NAME.getValue() + propertyName); + //GeneralUIUtils.ultimateWait(); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/MainRightContainer.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/MainRightContainer.java new file mode 100644 index 0000000000..3b9d5a8082 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/MainRightContainer.java @@ -0,0 +1,54 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +/** + * Represents the "w-sdc-main-right-container" panel that shows the list of resources/components. + */ +public class MainRightContainer { + + public static final String CSS_CLASS = "w-sdc-main-right-container"; + + private MainRightContainer() { + + } + + /** + * Checks if the resource is visible in the panel/container. + * + * @param resourceName the resource name to search in the panel/container + * @return {@code true} if the resource is visible, {@code false} otherwise. + */ + public static boolean isResultVisible(final String resourceName) { + return GeneralUIUtils.isElementVisibleByTestId(resourceName); + } + + /** + * Checks if the panel/container is showing no resources. + * + * @return {@code true} if the panel/container is empty, {@code false} otherwise. + */ + public static boolean isEmptyResult() { + return GeneralUIUtils.isElementInvisibleByTestId("dashboard-Elements"); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OnboardHeaderComponent.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OnboardHeaderComponent.java new file mode 100644 index 0000000000..cb2fcc261f --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OnboardHeaderComponent.java @@ -0,0 +1,91 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; + +import static org.onap.sdc.frontend.ci.tests.pages.OnboardHeaderComponent.XpathSelector.MAIN_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.OnboardHeaderComponent.XpathSelector.ONBOARD_TAB_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.OnboardHeaderComponent.XpathSelector.WORKSPACE_TAB_DIV; + +/** + * Handles the Onboard Header Component UI test actions + */ +public class OnboardHeaderComponent extends AbstractPageObject { + + private WebElement wrappingElement; + + public OnboardHeaderComponent(final WebDriver webDriver) { + super(webDriver); + } + + @Override + public void isLoaded() { + wrappingElement = getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(MAIN_DIV.getXpath()))); + getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(WORKSPACE_TAB_DIV.getXpath()))); + getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(ONBOARD_TAB_DIV.getXpath()))); + } + + /** + * Clicks on the workspace tab. + */ + public void clickOnWorkspaceTab() { + wrappingElement.findElement(By.xpath(WORKSPACE_TAB_DIV.getXpath())); + } + + /** + * Clicks on the workspace tab. + */ + public void clickOnOnboardTab() { + wrappingElement.findElement(By.xpath(ONBOARD_TAB_DIV.getXpath())); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + MAIN_DIV("onboard-header", "//div[contains(@class, '%s')]"), + WORKSPACE_TAB_DIV("onboard-workspace-tab", "//div[@data-test-id='%s']"), + ONBOARD_TAB_DIV("onboard-onboard-tab", "//div[@data-test-id='%s']"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OnboardHomePage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OnboardHomePage.java new file mode 100644 index 0000000000..5b47233a5c --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OnboardHomePage.java @@ -0,0 +1,87 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; + +import static org.onap.sdc.frontend.ci.tests.pages.OnboardHomePage.XpathSelector.ADD_NEW_VLM_BTN; +import static org.onap.sdc.frontend.ci.tests.pages.OnboardHomePage.XpathSelector.ADD_NEW_VSP_BTN; + +/** + * Handles the Onboard Home Page UI test actions + */ +public class OnboardHomePage extends AbstractPageObject { + + private final OnboardHeaderComponent onboardHeaderComponent; + private WebElement createNewVspBtn; + + public OnboardHomePage(final WebDriver webDriver, + final OnboardHeaderComponent onboardHeaderComponent) { + super(webDriver); + this.onboardHeaderComponent = onboardHeaderComponent; + } + + @Override + public void isLoaded() { + onboardHeaderComponent.isLoaded(); + createNewVspBtn = getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(ADD_NEW_VSP_BTN.getXpath()))); + getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(ADD_NEW_VLM_BTN.getXpath()))); + } + + /** + * Clicks on the button create new vsp. + * + * @return returns the next vsp creation page object + */ + public VspCreationModal clickOnCreateNewVsp() { + createNewVspBtn.click(); + return new VspCreationModal(webDriver); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + ADD_NEW_VSP_BTN("catalog-add-new-vsp", "//div[@data-test-id='%s']"), + ADD_NEW_VLM_BTN("catalog-add-new-vlm", "//div[@data-test-id='%s']"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OpsOperationPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OpsOperationPage.java new file mode 100644 index 0000000000..ffd82b0fff --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/OpsOperationPage.java @@ -0,0 +1,160 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import java.util.List; + +public class OpsOperationPage { + + private static final int WEB_DRIVER_TIME_OUT = 90; + private static final int MAX_WAITING_PERIOD_MS = 5 * 60 * 1000; + private static final int NAP_PERIOD = 10000; + private static final int MAX_WAITING_PERIOF_DIVIDER = 1000; + + private OpsOperationPage() { + super(); + } + + public static void distributeService() { + SetupCDTest.getExtendTest().log(Status.INFO, "Distributing"); + clickOnButton(DataTestIdEnum.DistributionChangeButtons.DISTRIBUTE); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.MONITOR.getValue()); + } + + public static void displayMonitor() { + GeneralUIUtils.moveToStep(StepsEnum.MONITOR); + } + + public static void reDistributeService() { + SetupCDTest.getExtendTest().log(Status.INFO, "Redistributing..."); + clickOnButton(DataTestIdEnum.DistributionChangeButtons.RE_DISTRIBUTE); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DistributionChangeButtons.MONITOR.getValue()); + } + + private static void clickOnButton(DataTestIdEnum.DistributionChangeButtons button) { + GeneralUIUtils.getWebElementByTestID(button.getValue()).click(); + GeneralUIUtils.waitForLoader(); + } + + public static List<WebElement> getRowsFromMonitorTable() { + SetupCDTest.getExtendTest().log(Status.INFO, "Counting the rows from the distribution table"); + GeneralPageElements.checkElementsCountInTable(1, () -> GeneralUIUtils.getWebElementsListByTestID("ditributionTable")); + List<WebElement> distributionRecords = GeneralUIUtils.getWebElementsListByTestID("ditributionTable"); + List<WebElement> findElements = distributionRecords.get(0).findElements(By.className("w-sdc-distribute-parent-block")); + return findElements; + } + + public static void showDistributionStatus(int rowIndex) { + GeneralUIUtils.getWebElementByTestID("ShowRecordButton_" + String.valueOf(rowIndex)).click(); + GeneralUIUtils.waitForLoader(); + } + + public static String getTotalArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("totalArtifacts_" + String.valueOf(rowIndex)).getText(); + } + + public static String getNotifiedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("notified_" + String.valueOf(rowIndex)).getText(); + } + + public static String getDownloadedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("downloaded_" + String.valueOf(rowIndex)).getText(); + } + + public static String getDeployedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("deployed_" + String.valueOf(rowIndex)).getText(); + } + + public static String getNotNotifiedArtifactsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("NotNotified_" + String.valueOf(rowIndex)).getText(); + } + + public static String getErrorsSum(int rowIndex) { + return GeneralUIUtils.getWebElementByTestID("errors_" + String.valueOf(rowIndex)).getText(); + } + + public static void clickRefreshTableButton(int rowIndex) { + GeneralUIUtils.getWebElementByTestID("refreshButton").click(); + // wait until total artifacts field disappear + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), WEB_DRIVER_TIME_OUT); + wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@data-tests-id='" + "totalArtifacts_" + String.valueOf(rowIndex) + "']"))); + } + + public static void waitUntilArtifactsDistributed(int rowIndex) throws Exception { + waitUntilArtifactsDistributed("0", 0); + } + + public static void waitUntilArtifactsDistributed(String expectedArtifactsSum, int rowIndex) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Waiting until all artifacts are distributed"); + boolean isKeepWaiting = true; + int maxWaitingPeriodMS = MAX_WAITING_PERIOD_MS; + int sumWaitingTime = 0; + int napPeriod = NAP_PERIOD; + while (isKeepWaiting) { + showDistributionStatus(rowIndex); + String actualTotalArtifactsSize = getTotalArtifactsSum(rowIndex); + String actualNotifiedArtifactsSize = getNotifiedArtifactsSum(rowIndex); + String actualDownloadedArtifactsSize = getDownloadedArtifactsSum(rowIndex); + String actualDeployedArtifactsSize = getDeployedArtifactsSum(rowIndex); + String actualNotNotifedArtifactsSize = getNotNotifiedArtifactsSum(rowIndex); + isKeepWaiting = !actualTotalArtifactsSize.equals(actualDownloadedArtifactsSize) + || !actualTotalArtifactsSize.equals(actualNotifiedArtifactsSize) + || !actualTotalArtifactsSize.equals(actualDeployedArtifactsSize) + || actualTotalArtifactsSize.equals("0") || actualDownloadedArtifactsSize.equals("0") + || actualNotifiedArtifactsSize.equals("0") || actualDeployedArtifactsSize.equals("0"); + + if (isKeepWaiting) { + + if (Integer.parseInt(actualNotNotifedArtifactsSize) > 1) { + SetupCDTest.getExtendTest().log(Status.INFO, "Some artifacts are not notified"); + isKeepWaiting = false; + throw new Exception("Some artifacts are not notified..."); + } + + GeneralUIUtils.sleep(napPeriod); + sumWaitingTime += napPeriod; + + if (sumWaitingTime > maxWaitingPeriodMS) { + SetupCDTest.getExtendTest().log(Status.INFO, "Not all artifacts are displayed"); + isKeepWaiting = false; + throw new Exception(String.format("Not all artifacts are displayed withing %s seconds", + String.valueOf(maxWaitingPeriodMS / MAX_WAITING_PERIOF_DIVIDER))); + } + + clickRefreshTableButton(rowIndex); + } + } + + SetupCDTest.getExtendTest().log(Status.INFO, "All artifacts were successfully distributed"); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PageObject.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PageObject.java new file mode 100644 index 0000000000..eb31c18f23 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PageObject.java @@ -0,0 +1,34 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +/** + * Represents represents a page or component in a html page + */ +@FunctionalInterface +public interface PageObject { + + /** + * Checks if the Page Object is loaded on the browser. Any problem during the checking should throw + * a custom RuntimeException. + */ + void isLoaded(); + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ProductGeneralPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ProductGeneralPage.java new file mode 100644 index 0000000000..db5f0f0369 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ProductGeneralPage.java @@ -0,0 +1,117 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ProductReqDetails; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.ArrayList; + +/** + * @author al714h + */ + +public class ProductGeneralPage extends ResourceGeneralPage { + + private ProductGeneralPage() { + super(); + } + + public static ProductLeftMenu getProductLeftMenu() { + return new ProductLeftMenu(); + } + + public static void defineName(String productName) { + WebElement productNameTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.PRODUCT_NAME.getValue()); + productNameTextbox.clear(); + productNameTextbox.sendKeys(productName); + } + + public static void defineFullName(String productFullName) { + WebElement productFullNameTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.FULL_NAME.getValue()); + productFullNameTextbox.clear(); + productFullNameTextbox.sendKeys(productFullName); + } + + public static void defineProjectCode(String pmat) { + WebElement pmattTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.PROJECT_CODE.getValue()); + pmattTextbox.clear(); + pmattTextbox.sendKeys(pmat); + } + + public static String getPmattText() { + return getPmattField().getAttribute("value"); + } + + public static String[] getTags() { + return getElementsFromTagsTable().stream().map(WebElement::getText).toArray(String[]::new); + } + + private static WebElement getPmattField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.PROJECT_CODE.getValue()); + } + + public static void deleteOldTags(ProductReqDetails product) { + // Delete tag elements + int i = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-delete").size(); + while (i > 0) { + GeneralUIUtils.getWebElementByTestID("i-sdc-tag-delete").click(); + i--; + } + + product.setTags(new ArrayList<String>()); + } + + public static void clickAddWorkflow() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding workflow...")); + GeneralUIUtils.clickOnElementByText("Add Workflow"); + } + + public static void fillAndAddNewWorkflow(String name, String description) throws InterruptedException { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling name field with %s", name)); + insertText(name, "label + input"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling description filed with %s", name)); + insertText(description, "label + textarea"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking save button ")); + clickSave(); + } + + public static void insertText(String artifactDescriptoin, String element) throws InterruptedException { + GeneralUIUtils.getElementsByCSS("div[class='modal-content']"); + WebElement artifactDescriptionTextbox = GeneralUIUtils.getWebElementBy(By.cssSelector(element)); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox.sendKeys(artifactDescriptoin); + GeneralUIUtils.ultimateWait(); + } + + public static void clickSave() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on Save button")); + GeneralUIUtils.clickOnElementByText("Save"); + GeneralUIUtils.ultimateWait(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ProductLeftMenu.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ProductLeftMenu.java new file mode 100644 index 0000000000..5680311144 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ProductLeftMenu.java @@ -0,0 +1,47 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +/** + * @author al714h + */ + +public class ProductLeftMenu implements ComponentLeftMenu { + + public void moveToGeneralScreen() throws Exception { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.GENERAL); + } + + public void moveToIconScreen() throws Exception { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.ICON); + } + + public void moveToCompositionScreen() throws Exception { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.COMPOSITION); + } + + public void moveToHierarchyScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.HIERARCHY); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertiesAssignmentPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertiesAssignmentPage.java new file mode 100644 index 0000000000..89806e202f --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertiesAssignmentPage.java @@ -0,0 +1,317 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.pages; + + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.PropertiesAssignmentScreen; +import org.onap.sdc.frontend.ci.tests.exception.PropertiesAssignmentPageException; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.Keys; +import org.openqa.selenium.NoSuchElementException; +import org.openqa.selenium.WebElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class PropertiesAssignmentPage { + + private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesAssignmentPage.class); + + private PropertiesAssignmentPage() { + + } + + public static void clickOnInputTab() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Input Tab"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.INPUTS_TAB.getValue()); + } + + public static void clickOnPropertiesTab() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Properties Tab"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.PROPERTIES_TAB.getValue()); + } + + public static void clickOnCompositionRightTab() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Composition Right Tab"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.COMPOSITION_TAB.getValue()); + } + + public static void clickOnPropertyStructureRightTab() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Property Structure Right Tab"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.PROPERTY_STRUCTURE_TAB.getValue()); + } + + public static void clickOnDeclareButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Declare Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.DECLARE_BUTTON.getValue()); + } + + public static void clickOnSaveButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Save Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.SAVE_BUTTON.getValue()); + } + + public static void clickOnDiscardButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Discard Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.DISCARD_BUTTON.getValue()); + } + + public static void clickOnDialogSaveButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Save Button in Dialog Popup"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.SAVE_DIALOG_SAVE.getValue()); + } + + public static void clickOnDialogDiscardButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Discard Button in Dialog Popup"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.SAVE_DIALOG_DISCARD.getValue()); + } + + public static void clickOnDialogCancelButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Cancel Button in Dialog Popup"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.SAVE_DIALOG_CANCEL.getValue()); + } + + public static void clickOnEditButton(String propertyName) { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Edit button "); + GeneralUIUtils.clickOnElementByTestId(PropertyNameBuilder.buildPopupField(propertyName)); + } + + public static void clickOnSetButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Set button in a property popup "); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_SET_BUTTON.getValue()); + } + + public static void clickOnExpandButton(String propertyName, int index) { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Expand Complex Property Button"); + GeneralUIUtils.clickOnElementByTestId(PropertyNameBuilder.buildIExpandButton(propertyName, index)); + } + + public static void findSearchBoxAndClick(final String resourceName) throws PropertiesAssignmentPageException { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " in Properties"); + try { + final WebElement searchTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.SEARCH_BOX.getValue()); + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + GeneralUIUtils.ultimateWait(); + } catch (final Exception e) { + final String errorMsg = String.format("Could not interact with search bar, test id '%s'", + PropertiesAssignmentScreen.SEARCH_BOX.getValue()); + LOGGER.error(errorMsg, e); + SetupCDTest.getExtendTest().log(Status.ERROR, errorMsg); + throw new PropertiesAssignmentPageException(errorMsg, e); + } + + try { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component in Properties", resourceName)); + GeneralUIUtils.clickOnElementByInputTestIdWithoutWait(resourceName); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } catch (final Exception e) { + final String errorMsg = String.format("Could not click on component named '%s'", resourceName); + LOGGER.error(errorMsg, e); + SetupCDTest.getExtendTest().log(Status.ERROR, errorMsg); + throw new PropertiesAssignmentPageException(errorMsg, e); + } + } + + private static void clickOnProperty(String propertyName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the %s component in Properties", propertyName)); + GeneralUIUtils.clickOnElementByTestId(propertyName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } + + public static void clickOnAddValueToList(String propertyName) throws Exception { + try { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the Add To List button of %s component in Properties", propertyName)); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.ADD_TO_LIST_BUTTON.getValue() + propertyName); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Can't click on Add To List button of component named " + propertyName); + e.printStackTrace(); + } + } + + public static void clickODeleteValueFromList(String propertyName, int index) throws Exception { + try { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on the Delete From List button of %s component in Properties", propertyName)); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.DELETE_FROM_LIST_BUTTON.getValue() + propertyName + "." + index); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue()); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Can't click on Delete From List button of component named " + propertyName); + e.printStackTrace(); + } + } + + public static void clickOnDeleteInputButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Delete Input Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.INPUT_DELETE_BUTTON.getValue()); + } + + public static void clickOnDeleteInputDialogConfirmationButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Delete Input Dialog Confirmation Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.INPUT_DELETE_DIALOG_DELETE.getValue()); + } + + public static void clickOnComponentInComposition(final String resourceName) throws Exception { + SetupCDTest.getExtendTest() + .log(Status.INFO, String.format("Clicking on the %s component on Properties screen", resourceName)); + try { + GeneralUIUtils.clickOnElementByTestId(resourceName); + } catch (final Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Can't click on component named " + resourceName); + throw e; + } + } + + public static void findInput(String componentName, String resourceName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + componentName + "_" + resourceName + " on Inputs screen"); + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.SEARCH_BOX.getValue()); + String searchPattern = componentName + "_" + resourceName; + + searchTextbox.clear(); + searchTextbox.sendKeys(searchPattern); + GeneralUIUtils.ultimateWait(); + } + + public static void findProperty(String resourceName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " property on Properties screen"); + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.SEARCH_BOX.getValue()); + + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + GeneralUIUtils.ultimateWait(); + } + + public static void editPropertyValue(String resourceName, String value) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " property on Properties screen"); + WebElement valueTextbox = GeneralUIUtils.getWebElementByTestID(resourceName); + + clickOnProperty(resourceName); + valueTextbox.clear(); + SetupCDTest.getExtendTest().log(Status.INFO, "Editing " + resourceName + " property on Properties screen"); + valueTextbox.sendKeys(value); + GeneralUIUtils.ultimateWait(); + + } + + public static void deletePropertyValue(String resourceName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " property on Properties screen"); + WebElement valueTextbox = GeneralUIUtils.getWebElementByTestID(resourceName); + + clickOnProperty(resourceName); + SetupCDTest.getExtendTest().log(Status.INFO, "Deleting " + resourceName + " property on Properties screen"); + valueTextbox.sendKeys(Keys.chord(Keys.CONTROL, "a")); + valueTextbox.sendKeys(Keys.BACK_SPACE); + GeneralUIUtils.ultimateWait(); + + } + + + public static Boolean isPropertyChecked(String resourceName) { +// TODO add better implementation for css string + GeneralUIUtils.ultimateWait(); + Boolean isDisabled = GeneralUIUtils.checkForDisabledAttributeInHiddenElement("checkbox[data-tests-id='" + resourceName + "'] input"); + SetupCDTest.getExtendTest().log(Status.INFO, "Is property checkbox disabled? " + isDisabled); + return isDisabled; + } + + public static boolean isButtonDisabled(String dataTestId) { + return GeneralUIUtils.checkForDisabledAttribute(dataTestId); + } + + public static String selectBooleanPropertyValue(String propertyName, String propertyValue) { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + propertyName + " property on Properties screen"); + String actualPropertyValue = null; + try { + actualPropertyValue = GeneralUIUtils.getSelectedElementFromDropDown(propertyName).getText(); + } catch (NoSuchElementException e) { + SetupCDTest.getExtendTest().log(Status.INFO, "#selectBooleanPropertyValue - Failed to get selected boolean property value "); + SetupCDTest.getExtendTest().log(Status.INFO, e); + } + try { + GeneralUIUtils.getSelectList(propertyValue, propertyName); + } catch (NoSuchElementException e) { + e.printStackTrace(); + } + return actualPropertyValue; + } + + + //Filter Actions + public static void clickOnFilterButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter button "); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_BUTTON.getValue()); + } + + public static void clickOnFilterAllCheckbox() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter All Checkbox "); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_ALL.getValue()); + } + + public static void clickOnFilterCPCheckbox() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter CP Checkbox "); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_CP.getValue()); + } + + public static void clickOnFilterVfcCheckbox() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter VFC Checkbox "); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_VFC.getValue()); + } + + public static void clickOnFilterVlCheckbox() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter VL Checkbox "); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CHECKBOX_VL.getValue()); + } + + public static void clickOnFilterApplyButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter Apply Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_APPLY_BUTTON.getValue()); + } + + public static void clickOnFilterCloseButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter Close Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.FILTER_CLOSE_BUTTON.getValue()); + } + + public static void clickOnFilterClearAllButton() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Filter Clear All Button"); + GeneralUIUtils.clickOnElementByTestId(PropertiesAssignmentScreen.CLEAR_FILTER_BUTTON.getValue()); + } + + public static void findFilterBoxAndClick(String resourceName) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, "Searching for " + resourceName + " property in Properties table"); + WebElement searchTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesAssignmentScreen.FILTER_BOX.getValue()); + try { + searchTextbox.clear(); + searchTextbox.sendKeys(resourceName); + GeneralUIUtils.ultimateWait(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.INFO, "Can't interact with search bar"); + e.printStackTrace(); + } + + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertiesPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertiesPage.java new file mode 100644 index 0000000000..f914061a22 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertiesPage.java @@ -0,0 +1,82 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class PropertiesPage extends GeneralPageElements { + + private static final int WAIT_FOR_ELEMENT_TIME_OUT = 10; + + private PropertiesPage() { + super(); + } + + public static List<WebElement> getElemenetsFromTable() { + return GeneralUIUtils.getInputElements(DataTestIdEnum.PropertiesPageEnum.PROPERTY_ROW.getValue()); + } + + public static void clickAddPropertyArtifact() { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.ADD_NEW_PROPERTY.getValue()).click(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.POPUP_FORM.getValue()); + } + + public static void clickEditPropertyArtifact(String propertyName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.EDIT_PROPERTY.getValue() + propertyName).click(); + } + + public static void clickDeletePropertyArtifact(String propertyName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Delete property %s", propertyName)); + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue() + propertyName); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPageEnum.DELETE_PROPERTY.getValue() + propertyName); + GeneralPageElements.clickOKButton(); + GeneralUIUtils.waitForElementInVisibilityBy(By.className("w-sdc-modal-confirmation"), WAIT_FOR_ELEMENT_TIME_OUT); + } + + public static void clickDeletePropertyFromPopup(String propertyName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Delete property %s", propertyName)); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue() + propertyName); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.PropertiesPageEnum.DELETE_PROPERTY_POPUP.getValue()); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.OK.getValue()); + } + + public static void clickOnProperty(String propertyName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue() + propertyName).click(); + } + + public static PropertyPopup getPropertyPopup() { + return new PropertyPopup(); + } + + public static boolean verifyTotalProperitesField(int count) { + String totalPropertiesCount = GeneralUIUtils.getWebElementBy(By.id("properties-count")).getText(); + return ("Total Properties: " + count).equals(totalPropertiesCount); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertyNameBuilder.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertyNameBuilder.java new file mode 100644 index 0000000000..3adeaf17a8 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertyNameBuilder.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.pages; + +import org.openecomp.sdc.be.model.ComponentInstance; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; + +public class PropertyNameBuilder { + private static final String PREFIX_VAL = DataTestIdEnum.PropertiesAssignmentScreen.PROPERTY_VALUE_FIELD_PREFIX.getValue(); + private static final String PREFIX_KEY = DataTestIdEnum.PropertiesAssignmentScreen.PROPERTY_KEY_FIELD_PREFIX.getValue(); + private static final String PREFIX_EXPAND = DataTestIdEnum.PropertiesAssignmentScreen.EXPAND_BUTTON.getValue(); + private static final String PREFIX_INPUT_VAL = DataTestIdEnum.PropertiesAssignmentScreen.INPUT_VALUE_FIELD_PREFIX.getValue(); + private static final String POPUP_VAL = DataTestIdEnum.PropertiesAssignmentScreen.POPUP_VALUE_FIELD_PREFIX.getValue(); + + private PropertyNameBuilder() { + + } + + //VF/Service simple property value field + public static String buildSimpleField(String propertyName) { + return new StringBuilder().append(PREFIX_VAL).append(propertyName).toString(); + } + + public static String buildPopupField(String propertyName) { + return new StringBuilder().append(POPUP_VAL).append(propertyName).toString(); + } + + public static String buildIndexedField(String propertyName, int index) { + return new StringBuilder().append(PREFIX_VAL).append(propertyName).append(".").append(index).toString(); + } + + public static String buildIndexedKeyField(String propertyName, int index) { + return new StringBuilder().append(PREFIX_KEY).append(propertyName).append(".").append(index).toString(); + } + + public static String buildIComplexField(String propertyName, String nestedProperty) { + return new StringBuilder().append(PREFIX_VAL).append(propertyName).append(".").append(nestedProperty).toString(); + } + + public static String buildIComplexListField(String propertyName, String nestedProperty, int index) { + return new StringBuilder().append(PREFIX_VAL).append(propertyName).append(".").append(index).append(".").append(nestedProperty).toString(); + } + + public static String buildIExpandButton(String propertyName, int index) { + return new StringBuilder().append(PREFIX_EXPAND).append(propertyName).append(".").append(index).toString(); + } + + + //VF input value field + public static String buildDeclaredInputField(String componentName, String propertyName) { + return new StringBuilder().append(PREFIX_INPUT_VAL).append(componentName).append("_").append(propertyName).toString(); + } + + public static String buildInputField(String propertyName) { + return new StringBuilder().append(PREFIX_INPUT_VAL).append(propertyName).toString(); + } + + //Service Property value field - declared from VF + public static String buildServicePropertyValue(String componentName, String propertyName) { + return new StringBuilder().append(PREFIX_VAL).append(componentName).append("_").append(propertyName).toString(); + } + + //Service Input Name + public static String buildServiceInputNameServiceLevel(ComponentInstance componentInstance, String propertyName) { + return new StringBuilder().append(componentInstance.getNormalizedName()) + .append("_").append(propertyName).toString(); + } + + public static String buildServiceInputNameVfLevel(ComponentInstance componentInstance, String componentName, String propertyName) { + return new StringBuilder().append(componentInstance.getNormalizedName()) + .append("_").append(componentName).append("_").append(propertyName).toString(); + } + + + //Service Input Value + public static String buildVfDeclaredPropValue(String componentName, String propertyName) { + String inputName = componentName + "_" + propertyName; + return new StringBuilder().append("{\"get_input\":\"").append(inputName).append("\"}").toString(); + } + + public static String buildServiceDeclaredPropertyValue(ComponentInstance componentInstance, String componentName, String propertyName) { + String inputName = buildServiceInputNameVfLevel(componentInstance, componentName, propertyName); + return new StringBuilder().append("{\"get_input\":\"").append(inputName).append("\"}").toString(); + } + + public static String buildServiceDeclaredPropValueServiceLevel(ComponentInstance componentInstance, String propertyName) { + String inputName = buildServiceInputNameServiceLevel(componentInstance, propertyName); + return new StringBuilder().append("{\"get_input\":\"").append(inputName).append("\"}").toString(); + } + + //Service Input value field + public static String buildServiceDeclaredFieldServiceLevel(ComponentInstance componentInstance, String propertyName) { + String inputName = buildServiceInputNameServiceLevel(componentInstance, propertyName); + return new StringBuilder().append(PREFIX_INPUT_VAL).append(inputName).toString(); + } + + public static String buildServiceDeclaredFieldVfLevel(ComponentInstance componentInstance, String componentName, String propertyName) { + String inputName = buildServiceInputNameVfLevel(componentInstance, componentName, propertyName); + return new StringBuilder().append(PREFIX_INPUT_VAL).append(inputName).toString(); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertyPopup.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertyPopup.java new file mode 100644 index 0000000000..64af785f70 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/PropertyPopup.java @@ -0,0 +1,108 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.NoSuchElementException; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; + +public class PropertyPopup { + + + private static final int WAIT_FOR_ELEMENT_TIME_OUT = 60; + + private boolean getPopupForm() { + return GeneralUIUtils.waitForElementInVisibilityByTestId(DataTestIdEnum.PropertiesPageEnum.POPUP_FORM.getValue(), WAIT_FOR_ELEMENT_TIME_OUT); + } + + public void insertPropertyName(String name) { + WebElement propertyNameField = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_NAME.getValue()); + propertyNameField.clear(); + propertyNameField.sendKeys(name); + } + + public void insertPropertyDefaultValue(String value) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Inserting to property default value: %s ", value)); + WebElement selectedType = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_TYPE.getValue())).getFirstSelectedOption(); + if (selectedType.getText().equals("boolean")) { + GeneralUIUtils.getSelectList(value, DataTestIdEnum.PropertiesPopupEnum.PROPERTY_BOOLEAN_VALUE.getValue()); + } else { + WebElement propertyValue = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_VALUE.getValue()); + propertyValue.clear(); + propertyValue.sendKeys(value); + } + + GeneralUIUtils.ultimateWait(); + } + + public void insertPropertyDescription(String description) { + WebElement propertyDescription = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_DESCRIPTION.getValue()); + propertyDescription.clear(); + propertyDescription.sendKeys(description); + } + + public void selectPropertyType(String propertyType) { + boolean isEntrySchemaDisplayed; + try { + GeneralUIUtils.getSelectList(propertyType, DataTestIdEnum.PropertiesPopupEnum.PROPERTY_TYPE.getValue()); + isEntrySchemaDisplayed = GeneralUIUtils.getDriver().findElement(By.xpath(DataTestIdEnum.PropertiesPopupEnum.ENTRY_SCHEMA.getValue())).isDisplayed(); + if (isEntrySchemaDisplayed) { + PropertiesPage.getPropertyPopup().selectEntrySchema(propertyType); + } + } catch (NoSuchElementException e) { + + } + } + + public void selectEntrySchema(String propertyType) { + GeneralUIUtils.getSelectList(propertyType, DataTestIdEnum.PropertiesPopupEnum.ENTRY_SCHEMA.getValue()); + } + + public void clickAdd() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.ADD.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public void clickSave() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.SAVE.getValue()); + getPopupForm(); + } + + public void clickCancel() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.CANCEL.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public void clickDone() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.PropertiesPopupEnum.DONE.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public void selectPropertyRadioButton(String propertyName) { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_RADIO_BUTTON_CONTAINER.getValue() + propertyName).findElement(By.className(DataTestIdEnum.PropertiesPopupEnum.RADIO_BUTTON_CLASS.getValue())).click(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceCreatePage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceCreatePage.java new file mode 100644 index 0000000000..08724c9a98 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceCreatePage.java @@ -0,0 +1,99 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.frontend.ci.tests.utilities.LoaderHelper; +import org.onap.sdc.frontend.ci.tests.utilities.NotificationHelper; +import org.onap.sdc.frontend.ci.tests.utilities.NotificationHelper.NotificationType; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; +import static org.onap.sdc.frontend.ci.tests.pages.ResourceCreatePage.XpathSelector.FORM_LIFE_CYCLE_STATE; + +/** + * Handles the Resource Create Page UI actions + */ +public class ResourceCreatePage extends AbstractPageObject { + + private static final Logger LOGGER = LoggerFactory.getLogger(ResourceCreatePage.class); + private final LoaderHelper loaderHelper; + private final NotificationHelper notificationHelper; + private WebElement createBtn; + + public ResourceCreatePage(final WebDriver webDriver, final LoaderHelper loaderHelper, + final NotificationHelper notificationHelper) { + super(webDriver); + this.loaderHelper = loaderHelper; + this.notificationHelper = notificationHelper; + timeoutInSeconds = 5; + } + + @Override + public void isLoaded() { + LOGGER.debug("Waiting for element visibility with xpath '{}'", FORM_LIFE_CYCLE_STATE.getXpath()); + final WebElement lifeCycleState = waitForElementVisibility(FORM_LIFE_CYCLE_STATE.getXpath()); + assertThat("Life cycle state should be as expected", + lifeCycleState.getText(), is(equalToIgnoringCase(LifeCycleStateEnum.IN_DESIGN.getValue()))); + createBtn = getWait() + .until(ExpectedConditions.elementToBeClickable(By.xpath(XpathSelector.CREATE_BTN.getXpath()))); + } + + /** + * Creates the resource and wait for success notification. + */ + public void createResource() { + createBtn.click(); + loaderHelper.waitForLoader(60); + notificationHelper.waitForNotification(NotificationType.SUCCESS, 60); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + CREATE_BTN("create/save", "//button[@data-tests-id='%s']"), + FORM_LIFE_CYCLE_STATE("formlifecyclestate", "//span[@data-tests-id='%s']"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceGeneralPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceGeneralPage.java new file mode 100644 index 0000000000..5fa9e04c50 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceGeneralPage.java @@ -0,0 +1,188 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.backend.ci.tests.datatypes.ComponentReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; + +import java.util.ArrayList; +import java.util.List; + + +public class ResourceGeneralPage extends GeneralPageElements { + + private static final int SLEEP_DURATION = 500; + + protected ResourceGeneralPage() { + super(); + } + + public static WebElement getNameField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.RESOURCE_NAME.getValue()); + } + + public static WebElement getDescriptionField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.DESCRIPTION.getValue()); + } + + public static String getCategoryDataTestsIdAttribute() { + return DataTestIdEnum.ResourceMetadataEnum.CATEGORY.getValue(); + } + + public static WebElement getVendorNameField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.VENDOR_NAME.getValue()); + } + + public static WebElement getVendorReleaseField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.VENDOR_RELEASE.getValue()); + } + + public static WebElement getTagsField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.TAGS.getValue()); + } + + public static WebElement getContactIdField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ResourceMetadataEnum.CONTACT_ID.getValue()); + } + + /***************************************************************/ + + public static String getNameText() { + return getNameField().getAttribute("value"); + } + + public static void defineName(String resourceName) { + WebElement resourceNameTextbox = getNameField(); + resourceNameTextbox.clear(); + resourceNameTextbox.sendKeys(resourceName); + } + + public static void defineNameWithPaste() { + defineTextBoxWithPaste(getNameField()); + } + + public static String getDescriptionText() { + return getDescriptionField().getAttribute("value"); + } + + public static void defineDescription(String description) { + WebElement descriptionTextbox = getDescriptionField(); + descriptionTextbox.clear(); + descriptionTextbox.sendKeys(description); + } + + public static void defineDescriptionWithPaste() { + defineTextBoxWithPaste(getDescriptionField()); + } + + public static String getVendorNameText() { + return getVendorNameField().getAttribute("value"); + } + + public static void defineVendorName(String vendorName) { + WebElement vendorNameTextbox = getVendorNameField(); + vendorNameTextbox.clear(); + vendorNameTextbox.sendKeys(vendorName); + } + + public static void defineVendorNameWithPaste() { + defineTextBoxWithPaste(getVendorNameField()); + } + + public static String getVendorReleaseText() { + return getVendorReleaseField().getAttribute("value"); + } + + public static void defineVendorRelease(String vendorRelease) { + WebElement vendorReleaseTextbox = getVendorReleaseField(); + vendorReleaseTextbox.clear(); + vendorReleaseTextbox.sendKeys(vendorRelease); + } + + public static void defineVendorReleaseWithPaste() { + defineTextBoxWithPaste(getVendorReleaseField()); + } + + public static void defineTag(String resourceTags) { + WebElement tagTextbox = getTagsField(); + tagTextbox.clear(); + tagTextbox.sendKeys(resourceTags); + tagTextbox.sendKeys(Keys.ENTER); + } + + public static void defineTagsList(ComponentReqDetails component, String[] tags) { + List<String> taglist = new ArrayList<String>(); + WebElement resourceTagsTextbox = getTagsField(); + for (String tag : tags) { + resourceTagsTextbox.clear(); + resourceTagsTextbox.sendKeys(tag); + GeneralUIUtils.sleep(SLEEP_DURATION); + resourceTagsTextbox.sendKeys(Keys.ENTER); + taglist.add(tag); + } + component.getTags().addAll(taglist); + } + + public static void defineTagsListWithPaste() { + List<String> taglist = new ArrayList<String>(); + WebElement resourceTagsTextbox = getTagsField(); + defineTextBoxWithPaste(resourceTagsTextbox); + resourceTagsTextbox.sendKeys(Keys.ENTER); + } + + public static void defineCategory(String category) { + GeneralUIUtils.getSelectList(category, getCategoryDataTestsIdAttribute()); + } + + public static String getContactIdText() { + return getContactIdField().getAttribute("value"); + } + + public static void defineContactId(String userId) { + WebElement contactIdTextbox = getContactIdField(); + contactIdTextbox.clear(); + contactIdTextbox.sendKeys(userId); + GeneralUIUtils.waitForLoader(); + } + + public static List<WebElement> getElementsFromTagsTable() { + return GeneralUIUtils.getWebElementsListByTestID(DataTestIdEnum.ResourceMetadataEnum.TAGS_TABLE.getValue()); + } + + public static void defineTextBoxWithPaste(WebElement textBox) { + textBox.clear(); + textBox.sendKeys(Keys.CONTROL + "v"); + GeneralUIUtils.ultimateWait(); + } + + public static void moveToToscaArtifactsSectionAndDownloadTosca() { + getLeftMenu().moveToToscaArtifactsScreen(); + ToscaArtifactsPage.downloadCsar(); + } + + public static String getVersionUI() { + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum.GeneralElementsEnum.VERSION_HEADER.getValue()).getText().replace("V", ""); + return actualVersion; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceLeftMenu.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceLeftMenu.java new file mode 100644 index 0000000000..a504fc71e5 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceLeftMenu.java @@ -0,0 +1,71 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +public class ResourceLeftMenu implements ComponentLeftMenu { + + public void moveToGeneralScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.GENERAL); + } + + public void moveToIconScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.ICON); + } + + public void moveToDeploymentArtifactScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.DEPLOYMENT_ARTIFACT); + } + + public void moveToInformationalArtifactScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.INFORMATION_ARTIFACT); + } + + public void moveToPropertiesScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.PROPERTIES); + } + + public void moveToCompositionScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.COMPOSITION); + } + + public void moveToActivityLogScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.ACTIVITY_LOG); + } + + public void moveToDeploymentViewScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.DEPLOYMENT_VIEW); + } + + public void moveToToscaArtifactsScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.TOSCA_ARTIFACTS); + } + + public void moveToInputsScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.INPUTS); + } + + public void moveToPropertiesAssignmentScreen() { + GeneralUIUtils.moveToStep(DataTestIdEnum.StepsEnum.PROPERTIES_ASSIGNMENT); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceLeftSideMenu.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceLeftSideMenu.java new file mode 100644 index 0000000000..35c8b090e0 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourceLeftSideMenu.java @@ -0,0 +1,91 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; + +import static org.onap.sdc.frontend.ci.tests.pages.ResourceLeftSideMenu.XpathSelector.MAIN_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.ResourceLeftSideMenu.XpathSelector.PROPERTIES_ASSIGNMENT_MENU; + +/** + * Handles the Resource Page Left Side Menu UI actions + */ +public class ResourceLeftSideMenu extends AbstractPageObject { + + private WebElement wrappingElement; + + public ResourceLeftSideMenu(final WebDriver webDriver) { + super(webDriver); + timeoutInSeconds = 5; + } + + @Override + public void isLoaded() { + wrappingElement = getWrappingElement(); + } + + /** + * Gets the enclosing element of the menu. + * + * @return the enclosing element + */ + public WebElement getWrappingElement() { + return getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.className(MAIN_DIV.getId()))); + } + + /** + * Clicks on the properties assignment menu item. + * + * @return the next page object + */ + public ResourcePropertiesAssignmentPage clickOnPropertiesAssignmentMenuItem() { + wrappingElement.findElement(By.xpath(PROPERTIES_ASSIGNMENT_MENU.getXpath())).click(); + return new ResourcePropertiesAssignmentPage(webDriver); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + MAIN_DIV("w-sdc-left-sidebar", "//div[@class='%s']"), + PROPERTIES_ASSIGNMENT_MENU("Properties AssignmentLeftSideMenu", "//*[@data-tests-id='%s']"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourcePropertiesAssignmentPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourcePropertiesAssignmentPage.java new file mode 100644 index 0000000000..726a73f0cf --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ResourcePropertiesAssignmentPage.java @@ -0,0 +1,113 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; + +import java.util.ArrayList; +import java.util.List; + +import static org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.MAIN_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.NO_DATA_MESSAGE; +import static org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.PROPERTIES_TABLE; +import static org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.SOFTWARE_VERSION_INPUT; +import static org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.SOFTWARE_VERSION_PROPERTY_CHECKBOX; +import static org.onap.sdc.frontend.ci.tests.pages.ResourcePropertiesAssignmentPage.XpathSelector.TITLE_DIV; + +/** + * Handles the Resource Properties Assignment Page UI actions + */ +public class ResourcePropertiesAssignmentPage extends AbstractPageObject { + + private WebElement wrappingElement; + + public ResourcePropertiesAssignmentPage(final WebDriver webDriver) { + super(webDriver); + } + + @Override + public void isLoaded() { + wrappingElement = getWait(5) + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(MAIN_DIV.getXpath()))); + getWait(5) + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(TITLE_DIV.getXpath()))); + } + + /** + * Gets the software_version property values. + * + * @return the list of software versions found + */ + public List<String> getSoftwareVersionProperty() { + waitPropertiesToLoad(); + final By swVersionCheckboxLocator = By.xpath(SOFTWARE_VERSION_PROPERTY_CHECKBOX.getXpath()); + getWait(5).until(ExpectedConditions.visibilityOfElementLocated(swVersionCheckboxLocator)); + + final List<String> softwareVersionList = new ArrayList<>(); + final List<WebElement> elements = wrappingElement.findElements(By.xpath(SOFTWARE_VERSION_INPUT.getXpath())); + for (final WebElement element : elements) { + softwareVersionList.add(element.getAttribute("value")); + } + + return softwareVersionList; + } + + /** + * Waits for the properties loading. + */ + private void waitPropertiesToLoad() { + getWait(5) + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(PROPERTIES_TABLE.getXpath()))); + getWait(5) + .until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(NO_DATA_MESSAGE.getXpath()))); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + MAIN_DIV("w-sdc-main-right-container", "//div[@class='%s']"), + TITLE_DIV("tab-title", "//div[contains(@class,'%s') and contains(text(), 'Properties Assignment')]"), + PROPERTIES_TABLE("properties-table", "//div[contains(@class,'%s')]"), + NO_DATA_MESSAGE("no-data", "//div[contains(@class,'%s') and text()='No data to display']"), + SOFTWARE_VERSION_PROPERTY_CHECKBOX("software_versions", "//checkbox[@data-tests-id='%s']"), + SOFTWARE_VERSION_INPUT("value-prop-software_versions.", "//input[starts-with(@data-tests-id,'%s')]"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ServiceGeneralPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ServiceGeneralPage.java new file mode 100644 index 0000000000..775e599df6 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ServiceGeneralPage.java @@ -0,0 +1,182 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.openecomp.sdc.be.model.Service; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.ServiceMetadataEnum; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.frontend.ci.tests.verificator.ToscaValidation; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class ServiceGeneralPage extends ResourceGeneralPage { + + public static ServiceLeftMenu getServiceLeftMenu() { + return new ServiceLeftMenu(); + } + + public static void defineName(String serviceName) { + WebElement serviceNameTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.SERVICE_NAME.getValue()); + serviceNameTextbox.clear(); + serviceNameTextbox.sendKeys(serviceName); + } + + + public static void defineServiceFunction(String serviceFunction) { + WebElement serviceFunctionTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.SERVICE_FUNCTION.getValue()); + serviceFunctionTextbox.clear(); + serviceFunctionTextbox.sendKeys(serviceFunction); + } + + public static void defineProjectCode(String pmat) { + WebElement projectCodeTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE.getValue()); + projectCodeTextbox.clear(); + projectCodeTextbox.sendKeys(pmat); + } + public static void defineNamingPolicy(String namingPolicyText) { + WebElement namingPolicyTextbox = GeneralUIUtils + .getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.NAMING_POLICY.getValue()); + namingPolicyTextbox.clear(); + namingPolicyTextbox.sendKeys(namingPolicyText); + } + + public static String getServiceFunctionText(){ + return getServiceFunctionField().getAttribute("value"); + } + + public static String getNamingPolicyText(){ + return getNamingPolicyField().getAttribute("value"); + } + + private static WebElement getNamingPolicyField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.NAMING_POLICY.getValue()); + } + + + public static String getProjectCodeText() { + return getProjectCodeField().getAttribute("value"); + } + + public static String[] getTags() { + return getElementsFromTagsTable().stream().map(WebElement::getText).toArray(String[]::new); + } + private static WebElement getServiceFunctionField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.SERVICE_FUNCTION.getValue()); + } + + private static WebElement getProjectCodeField() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ServiceMetadataEnum.PROJECT_CODE.getValue()); + } + + public static void deleteOldTags(ServiceReqDetails service) { + // Delete tag elements + int i = GeneralUIUtils.getWebElementsListByTestID("i-sdc-tag-delete").size(); + while (i > 0) { + GeneralUIUtils.getWebElementByTestID("i-sdc-tag-delete").click(); + i--; + } + + service.setTags(new ArrayList<String>()); + } + + public static String getCategoryText() { + return GeneralUIUtils.getSelectedElementFromDropDown(getCategoryDataTestsIdAttribute()).getText(); + } + + public static List<WebElement> getCategories() { + return GeneralUIUtils.getElementFromDropDown(getCategoryDataTestsIdAttribute()).getOptions(); + } + + public static String getInstantiationTypeChosenValue() { + return GeneralUIUtils.getSelectedElementFromDropDown(getInstantiationTypeIdAttribute()).getText(); + } + + private static String getInstantiationTypeIdAttribute() { + return ServiceMetadataEnum.INSTANTIATION_TYPE.getValue(); + } + + public static void clickAddWorkflow() { + SetupCDTest.getExtendTest().log(Status.INFO, "Adding workflow..."); + GeneralUIUtils.clickOnElementByText("Add Workflow"); + } + + public static void fillAndAddNewWorkflow(String name, String description) throws InterruptedException { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling name field with %s", name)); + insertText(name, "label + input"); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Filling description filed with %s", name)); + insertText(description, "label + textarea"); + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking save button "); + clickSave(); + } + + public static void insertText(String artifactDescriptoin, String element) throws InterruptedException { + GeneralUIUtils.getElementsByCSS("div[class='modal-content']"); + WebElement artifactDescriptionTextbox = GeneralUIUtils.getWebElementBy(By.cssSelector(element)); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox.sendKeys(artifactDescriptoin); + GeneralUIUtils.ultimateWait(); + } + + public static void clickSave() { + SetupCDTest.getExtendTest().log(Status.INFO, "Clicking on Save button"); + GeneralUIUtils.clickOnElementByXpath("//*[@data-test-id='form-submit-button']"); + GeneralUIUtils.ultimateWait(); + } + + public static void defineInstantiationType(String instantiationType) { + GeneralUIUtils.getSelectList(instantiationType, DataTestIdEnum.ServiceMetadataEnum.INSTANTIATION_TYPE.getValue()); + } + + public Service prepareServiceObject(ServiceReqDetails serviceMetadata) throws Exception { + return AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, serviceMetadata.getName(), "0.1"); + } + + public static boolean parseToscaFileIntoServiceAndValidateProperties(ServiceReqDetails serviceMetadata) throws Exception { + ServiceGeneralPage serviceGeneralPageObject = new ServiceGeneralPage(); + Service service = serviceGeneralPageObject.prepareServiceObject(serviceMetadata); + Map<String, String> expectedMetadataMap = Utils.generateServiceMetadataToExpectedObject(serviceMetadata, service); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + ToscaDefinition toscaServiceDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(latestFilefromDir); + Either<Boolean, Map<String, Object>> serviceToscaMetadataValidator = ToscaValidation.serviceToscaMetadataValidator(expectedMetadataMap, toscaServiceDefinition); + return serviceToscaMetadataValidator.isRight(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ServiceLeftMenu.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ServiceLeftMenu.java new file mode 100644 index 0000000000..e9c764283a --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ServiceLeftMenu.java @@ -0,0 +1,32 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +public class ServiceLeftMenu implements ComponentLeftMenu { + + public void moveToManagmentWorkflow() throws Exception { + GeneralUIUtils.moveToStep(StepsEnum.MANAGEMENT_WORKFLOW); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/SoftwareProductOnboarding.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/SoftwareProductOnboarding.java new file mode 100644 index 0000000000..189cb5a6f0 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/SoftwareProductOnboarding.java @@ -0,0 +1,129 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.hamcrest.core.Is; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertThat; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.ATTACHMENT_VIEW; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.BNT_SUBMIT; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.FILE_INPUT; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.NAV_BAR_GROUP_ITEM_ATTACHMENT; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.NAV_BAR_GROUP_NAME_XPATH; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.ONBOARDING_LOADER_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.PAGE_MAIN_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.SoftwareProductOnboarding.XpathSelector.SELECTED_NAV_BAR_GROUP_ITEM; + +public class SoftwareProductOnboarding extends AbstractPageObject { + + private static final Logger LOGGER = LoggerFactory.getLogger(SoftwareProductOnboarding.class); + private static final String DIV_CLASS_XPATH_FORMAT = "//div[@class='%s']"; + private static final String DIV_DATA_TEST_ID_XPATH_FORMAT = "//div[@data-test-id='%s']"; + private final VspCommitModal vspCommitModal; + private WebElement wrappingElement; + + public SoftwareProductOnboarding(final WebDriver webDriver, + final VspCommitModal vspCommitModal) { + super(webDriver); + this.vspCommitModal = vspCommitModal; + timeoutInSeconds = 5; + } + + @Override + public void isLoaded() { + wrappingElement = getWrappingElement(); + } + + public String getResourceName() { + return wrappingElement.findElement(By.xpath(NAV_BAR_GROUP_NAME_XPATH.getXpath())).getText(); + } + + public void uploadFile(final String resourceFilePath) { + LOGGER.debug("Uploading file '{}'", resourceFilePath); + setInputValue(FILE_INPUT, resourceFilePath); + } + + public void attachmentScreenIsLoaded() { + final String attachmentViewXpath = String.format("%s%s", PAGE_MAIN_DIV.getXpath(), ATTACHMENT_VIEW.getXpath()); + waitForElementVisibility(By.xpath(attachmentViewXpath)); + waitForElementInvisibility(By.xpath(ONBOARDING_LOADER_DIV.getXpath())); + final WebElement selectedNavBarGroupItem = + findSubElement(wrappingElement, SELECTED_NAV_BAR_GROUP_ITEM.getXpath()); + final String selectedNavBarGroupItemTestId = selectedNavBarGroupItem.getAttribute("data-test-id"); + assertThat("Attachment menu should be selected", selectedNavBarGroupItemTestId, + Is.is(NAV_BAR_GROUP_ITEM_ATTACHMENT.getId())); + } + + public void submit() { + findSubElement(wrappingElement, BNT_SUBMIT.getXpath()).click(); + vspCommitModal.isLoaded(); + vspCommitModal.fillCommentWithDefaulMessage(); + vspCommitModal.submit(); + } + + public WebElement getWrappingElement() { + LOGGER.debug("Finding element with xpath '{}'", PAGE_MAIN_DIV.getXpath()); + return waitForElementVisibility(PAGE_MAIN_DIV.getXpath()); + + } + + public void setInputValue(final XpathSelector inputTestId, final String value) { + findSubElement(wrappingElement, inputTestId.getXpath()).sendKeys(value); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + PAGE_MAIN_DIV("software-product-view", DIV_CLASS_XPATH_FORMAT), + UPLOAD_CSAR("upload-btn", "//input[@data-test-id='%s']"), + FILE_INPUT("fileInput", "//input[@name='%s']"), + NAV_BAR_GROUP_ITEM_ATTACHMENT("navbar-group-item-SOFTWARE_PRODUCT_ATTACHMENTS", DIV_DATA_TEST_ID_XPATH_FORMAT), + BNT_SUBMIT("vc-submit-btn", DIV_DATA_TEST_ID_XPATH_FORMAT), + NAV_BAR_GROUP_NAME_XPATH("navbar-group-name", DIV_DATA_TEST_ID_XPATH_FORMAT), + SELECTED_NAV_BAR_GROUP_ITEM("navigation-group-item-name selected", DIV_CLASS_XPATH_FORMAT), + ONBOARDING_LOADER_DIV("onboarding-loader-backdrop", DIV_CLASS_XPATH_FORMAT), + ATTACHMENT_VIEW("vsp-attachments-view", DIV_CLASS_XPATH_FORMAT); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TesterOperationPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TesterOperationPage.java new file mode 100644 index 0000000000..7e1fdabb58 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TesterOperationPage.java @@ -0,0 +1,86 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +public class TesterOperationPage { + + private TesterOperationPage() { + + } + + public static void certifyComponent(String componentName) throws Exception { + clickStartTestingButton(); + clickAcceptCertificationButton(componentName); + } + + public static void clickAcceptCertificationButton(String componentName) throws Exception { + ExtentTestActions.log(Status.INFO, "Accepting certification of " + componentName); + String actionDuration = GeneralUIUtils.getActionDuration(() -> + { + try { + clickAcceptCertificationButtonWithoutDuration(componentName); + } catch (Exception e) { + e.printStackTrace(); + } + }); + ExtentTestActions.log(Status.INFO, componentName + " is certified", actionDuration); + + } + + public static void clickStartTestingButton() throws Exception { + ExtentTestActions.log(Status.INFO, "Starting to test"); + String actionDuration = GeneralUIUtils.getActionDuration(() -> { + try { + clickStartTestingButtonWithoutDuration(); + } catch (Exception e) { + e.printStackTrace(); + } + }); + ExtentTestActions.log(Status.INFO, "Ready for certification", actionDuration); + } + + + private static void clickAcceptCertificationButtonWithoutDuration(String componentName) throws Exception { + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.LifeCyleChangeButtons.ACCEPT.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ModalItems.ACCEPT_TESTING_MESSAGE.getValue()).sendKeys(componentName + " tested successfuly"); + GeneralPageElements.clickOKButton(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + } catch (Exception e) { + throw new Exception("Accepting certification of " + componentName + " failed"); + } + } + + private static void clickStartTestingButtonWithoutDuration() throws Exception { + try { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.LifeCyleChangeButtons.START_TESTING.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.LifeCyleChangeButtons.ACCEPT.getValue()); + } catch (Exception e) { + throw new Exception("Start testing failed"); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TopNavComponent.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TopNavComponent.java new file mode 100644 index 0000000000..8fc54194ee --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TopNavComponent.java @@ -0,0 +1,146 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.onap.sdc.frontend.ci.tests.pages.TopNavComponent.XpathSelector.ARROW_DROPDOWN; +import static org.onap.sdc.frontend.ci.tests.pages.TopNavComponent.XpathSelector.MAIN_MENU_ONBOARD_BTN; +import static org.onap.sdc.frontend.ci.tests.pages.TopNavComponent.XpathSelector.NAV; +import static org.onap.sdc.frontend.ci.tests.pages.TopNavComponent.XpathSelector.REPOSITORY_ICON; +import static org.onap.sdc.frontend.ci.tests.pages.TopNavComponent.XpathSelector.SUB_MENU_BUTTON_HOME; + +/** + * Handles the Top Navigation Component UI actions + */ +public class TopNavComponent extends AbstractPageObject { + + private static final Logger LOGGER = LoggerFactory.getLogger(TopNavComponent.class); + + private WebElement wrappingElement; + private By navLocator = By.xpath(NAV.getXpath()); + + public TopNavComponent(final WebDriver webDriver) { + super(webDriver); + timeoutInSeconds = 5; + } + + @Override + public void isLoaded() { + wrappingElement = getWrappingElement(); + } + + /** + * Gets the enclosing element of the component. + * + * @return the enclosing element + */ + public WebElement getWrappingElement() { + LOGGER.debug("Finding element with xpath '{}'", NAV.getXpath()); + return waitForElementVisibility(navLocator); + } + + /** + * Clicks on home link inside the first breadcrumb arrow. + */ + public void clickOnHome() { + hoverToBreadcrumbArrow(0); + final By homeButtonLocator = By.xpath(SUB_MENU_BUTTON_HOME.getXpath()); + getWait().until(ExpectedConditions.visibilityOfElementLocated(homeButtonLocator)); + getWait().until(ExpectedConditions.elementToBeClickable(homeButtonLocator)).click(); + getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(REPOSITORY_ICON.getXpath()))); + } + + /** + * Clicks on the VSP repository icon. + * + * @return the next page object + */ + public VspRepositoryModalComponent clickOnRepositoryIcon() { + wrappingElement.findElement(By.xpath(REPOSITORY_ICON.getXpath())).click(); + + return new VspRepositoryModalComponent(webDriver); + } + + /** + * Clicks on the Onboard button. + * + * @return the next page object + */ + public OnboardHomePage clickOnOnboard() { + wrappingElement.findElement(By.xpath(MAIN_MENU_ONBOARD_BTN.getXpath())).click(); + return new OnboardHomePage(DriverFactory.getDriver(), new OnboardHeaderComponent(DriverFactory.getDriver())); + } + + /** + * Hover to a breadcrumb arrow of the given position. + * + * @param arrowPosition the position of the arrow from left to right + * @return the hovered breadcrumb arrow element + */ + public WebElement hoverToBreadcrumbArrow(final int arrowPosition) { + final Actions actions = new Actions(GeneralUIUtils.getDriver()); + final List<WebElement> arrowElementList = getWait() + .until( + ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(ARROW_DROPDOWN.getXpath()))); + final WebElement selectedArrowElement = arrowElementList.get(arrowPosition); + actions.moveToElement(selectedArrowElement).perform(); + return selectedArrowElement; + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + NAV("top-nav", "//nav[@class='%s']"), + SUB_MENU_BUTTON_HOME("sub-menu-button-home", "//*[@data-tests-id='%s']"), + ARROW_DROPDOWN("triangle-dropdown", "//li[contains(@class, '%s')]"), + MAIN_MENU_ONBOARD_BTN("main-menu-button-onboard", "//a[@data-tests-id='%s']"), + REPOSITORY_ICON("repository-icon", "//*[@data-tests-id='%s']"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TopSearchComponent.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TopSearchComponent.java new file mode 100644 index 0000000000..d284932bfb --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/TopSearchComponent.java @@ -0,0 +1,69 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; + +/** + * Represents the "top-search" search component in the main upper toolbar. + */ +public class TopSearchComponent { + + public static final String CSS_CLASS = "top-search"; + public static final String SEARCH_INPUT_TEST_ID = "main-menu-input-search"; + + private TopSearchComponent() { + + } + + /** + * Gets the search component input, waiting for it's visibility. + * + * @return search component input with test id {@link #SEARCH_INPUT_TEST_ID} + */ + public static WebElement getComponentInput() { + return GeneralUIUtils.getWebElementByTestID(SEARCH_INPUT_TEST_ID); + } + + /** + * Replaces the current search input value by the given value. This prevents to trigger the search twice by cleaning + * the input (triggers the search) and then pasting the value (triggers the search again). + * + * @param value the value to search + */ + public static void replaceSearchValue(final String value) { + replaceSearchValue(getComponentInput(), value); + } + + /** + * Replaces the current search input value by selecting it with Ctrl+A shortcut and pasting the given value. This + * prevents to trigger the search twice by cleaning the input (triggers the search) and then pasting the value + * (triggers the search again). + * + * @param searchTextInput input web element + * @param value the value to search + */ + public static void replaceSearchValue(final WebElement searchTextInput, final String value) { + searchTextInput.sendKeys(Keys.chord(Keys.CONTROL, "a"), value); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ToscaArtifactsPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ToscaArtifactsPage.java new file mode 100644 index 0000000000..bce341c310 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/ToscaArtifactsPage.java @@ -0,0 +1,59 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebElement; + +public class ToscaArtifactsPage extends DeploymentArtifactPage { + + private ToscaArtifactsPage() { + + } + + public static String getArtifactName(int row) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_NAME.getValue() + row).getText(); + } + + public static String getArtifactType(int row) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_TYPE.getValue() + row).getText(); + } + + public static String getArtifactVersion(int row) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_VERSION.getValue() + row).getText(); + } + + public static WebElement getArtifactDetails(int row) { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ToscaArtifactsScreenEnum.ARTIFACT_DETAILS.getValue() + row); + } + + public static void downloadCsar() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.DOWNLOAD_CSAR.getValue()); + //GeneralUIUtils.ultimateWait(); + } + + public static void downloadTemplate() { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ToscaArtifactsScreenEnum.TOSCA_TEMPLATE.getValue()); + //GeneralUIUtils.ultimateWait(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/UpgradeServicesPopup.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/UpgradeServicesPopup.java new file mode 100644 index 0000000000..9d33933985 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/UpgradeServicesPopup.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.pages; + +public class UpgradeServicesPopup { + + private UpgradeServicesPopup() { + + } + + private static boolean isUpgradePopupShown; + + public static boolean isUpgradePopupShown() { + return isUpgradePopupShown; + } + + static void setUpgradePopupShown(boolean upgradePopupShown) { + isUpgradePopupShown = upgradePopupShown; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/UploadArtifactPopup.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/UploadArtifactPopup.java new file mode 100644 index 0000000000..1e9a881b1b --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/UploadArtifactPopup.java @@ -0,0 +1,127 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; + +import java.io.File; + +public class UploadArtifactPopup { + + private static final int WAITING_FOR_ELEMENT_TIME_OUT = 10; + private boolean isCompositionPage; + + public UploadArtifactPopup(boolean isCompositionPage) { + super(); + this.isCompositionPage = isCompositionPage; + } + + public UploadArtifactPopup() { + super(); + } + + private WebElement getArtifactDescriptionWebElement() { + return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.ARTIFACT_DESCRIPTION.getValue()); + } + + public void loadFile(String path, String filename) { + final WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPopup.BROWSE.getValue()); + browseWebElement.sendKeys(path + File.separator + filename); + GeneralUIUtils.ultimateWait(); + } + + public void loadUndefinedFile(String path, String filename) { + final WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPopup.FILE_UNDEFINED.getValue()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Uploading file: %s", path + File.separator + filename)); + browseWebElement.sendKeys(path + File.separator + filename); + GeneralUIUtils.ultimateWait(); + } + + + public void insertDescription(String artifactDescriptoin) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Changing artifact description to: %s", artifactDescriptoin)); + WebElement artifactDescriptionTextbox = getArtifactDescriptionWebElement(); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox.sendKeys(artifactDescriptoin); + + GeneralUIUtils.ultimateWait(); + } + + public Select defineArtifactLabel(String requiredArtifactLabel) { + Select selectList = null; + WebElement artifactLabelWebElement; + + artifactLabelWebElement = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.ARTIFACT_LABEL.getValue()); + + + artifactLabelWebElement.clear(); + artifactLabelWebElement.sendKeys(requiredArtifactLabel); + return selectList; + } + + public void selectArtifactType(String artifactType) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPopup.ARTIFACT_TYPE_ICON.getValue()); + GeneralUIUtils.clickOnElementByTestId(artifactType); + } + + public void clickDoneButton() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForElementInVisibilityBy(By.className("sdc-add-artifact"), WAITING_FOR_ELEMENT_TIME_OUT); + } + + public void clickUpgradeArtifactsButton() throws Exception { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ModalItems.UPGRADE_ARTIFACT_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForElementInVisibilityBy(By.className("sdc-add-artifact"), WAITING_FOR_ELEMENT_TIME_OUT); + } + + public void clickCancelButton() throws Exception { + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.CANCEL_BUTTON.getValue()).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForElementInVisibilityByTestId("sdc-add-artifact"); + } + +// public void clickUpdateButton() throws Exception { +// clickAddButton(); +// GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ArtifactPopup.UPDATE_BUTTON.getValue()).click(); +// GeneralUIUtils.waitForLoader(); +// GeneralUIUtils.waitForElementInVisibilityByTestId(By.className("sdc-add-artifact"), 50); +// } + + public void insertURL(String artifactDescriptoin) throws Exception { + WebElement artifactDescriptionTextbox = getArtifactURLWebElement(); + artifactDescriptionTextbox.clear(); + artifactDescriptionTextbox.sendKeys(artifactDescriptoin); + } + + public WebElement getArtifactURLWebElement() { + return GeneralUIUtils.getWebElementBy(By.cssSelector((DataTestIdEnum.ArtifactPopup.URL.getValue()))); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspCommitModal.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspCommitModal.java new file mode 100644 index 0000000000..eb070e98a2 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspCommitModal.java @@ -0,0 +1,108 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.onap.sdc.frontend.ci.tests.pages.VspCommitModal.XpathSelector.COMMIT_AND_SUBMIT_BTN; +import static org.onap.sdc.frontend.ci.tests.pages.VspCommitModal.XpathSelector.COMMIT_COMMENT_TXT; +import static org.onap.sdc.frontend.ci.tests.pages.VspCommitModal.XpathSelector.MODAL_CANCEL_BTN; +import static org.onap.sdc.frontend.ci.tests.pages.VspCommitModal.XpathSelector.MODAL_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.VspCommitModal.XpathSelector.SUCCESS_MODAL_DIV; + +/** + * Handles the VSP Commit Modal UI actions + */ +public class VspCommitModal extends AbstractPageObject { + + private static final Logger LOGGER = LoggerFactory.getLogger(VspCommitModal.class); + + private WebElement wrappingElement; + + public VspCommitModal(final WebDriver webDriver) { + super(webDriver); + } + + public void isLoaded() { + LOGGER.debug("Finding element with xpath '{}'", MODAL_DIV.getXpath()); + wrappingElement = waitForElementVisibility(MODAL_DIV.getXpath()); + } + + /** + * Fills the comment text area with a default message. + */ + public void fillCommentWithDefaulMessage() { + final WebElement commentTxt = wrappingElement.findElement(By.xpath(COMMIT_COMMENT_TXT.getXpath())); + commentTxt.sendKeys("First VSP version"); + } + + /** + * Clicks on the modal submit and confirms success. + */ + public void submit() { + final WebElement commitAndSubmitBtn = wrappingElement.findElement(By.xpath(COMMIT_AND_SUBMIT_BTN.getXpath())); + commitAndSubmitBtn.click(); + GeneralUIUtils.ultimateWait(); + confirmSuccess(); + } + + /** + * Confirms the success of the modal submission. + */ + private void confirmSuccess() { + final WebElement successModal = getWait() + .until(ExpectedConditions.visibilityOfElementLocated(By.xpath(SUCCESS_MODAL_DIV.getXpath()))); + successModal.findElement(By.xpath(MODAL_CANCEL_BTN.getXpath())).click(); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + MODAL_DIV("sdc-modal-type-custom", "//div[contains(@class, '%s')]"), + COMMIT_AND_SUBMIT_BTN("form-submit-button", "//button[@data-test-id='%s']"), + COMMIT_COMMENT_TXT("commit-comment-text", "//textarea[@data-test-id='%s']"), + SUCCESS_MODAL_DIV("sdc-modal-type-info", "//div[contains(@class, '%s')]"), + MODAL_CANCEL_BTN("sdc-modal-cancel-button", "//button[@data-test-id='%s']"); + + private final String id; + private final String xpath; + + XpathSelector(final String id, final String xpath) { + this.id = id; + this.xpath = xpath; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpath, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspCreationModal.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspCreationModal.java new file mode 100644 index 0000000000..02cec1df41 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspCreationModal.java @@ -0,0 +1,161 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.onap.sdc.frontend.ci.tests.pages.VspCreationModal.XpathSelector.METHOD_RADIO; +import static org.onap.sdc.frontend.ci.tests.pages.VspCreationModal.XpathSelector.MODAL_XPATH; + +/** + * Handles the VSP Creation Modal UI actions + */ +public class VspCreationModal extends AbstractPageObject { + + private static final Logger LOGGER = LoggerFactory.getLogger(VspCreationModal.class); + + private WebElement wrappingElement; + + public VspCreationModal(final WebDriver webDriver) { + super(webDriver); + timeoutInSeconds = 5; + } + + @Override + public void isLoaded() { + LOGGER.debug("Finding element with xpath '{}'", MODAL_XPATH.getXpath()); + wrappingElement = waitForElementVisibility(MODAL_XPATH.getXpath()); + } + + /** + * Fills the creation form for the given vsp name. + * + * @param vspName the name of the Vendor Software Product + */ + public void fillCreationForm(final String vspName) { + fillName(vspName); + selectVendorFirstVendor(); + selectCategory("resourceNewCategory.network l4+.common network resources"); + fillDescription(vspName); + selectNetworkPackageOnboardingProcedure(); + } + + /** + * Clicks on the create button. + * + * @return the next page object + */ + public SoftwareProductOnboarding clickOnCreate() { + clickElement(XpathSelector.CREATE_BTN); + return new SoftwareProductOnboarding(webDriver, new VspCommitModal(webDriver)); + } + + /** + * Fills the VSP name. + * + * @param vspName the VSP name + */ + public void fillName(final String vspName) { + setInputValue(XpathSelector.NAME_TXT, vspName); + } + + /** + * Fills the VSP description. + * + * @param description the VSP description + */ + public void fillDescription(final String description) { + setInputValue(XpathSelector.DESCRIPTION_TXT, description); + } + + /** + * Selects the first vendor in the vendor list. + */ + public void selectVendorFirstVendor() { + setSelectIndex(XpathSelector.VENDOR_SELECT, 1); + } + + /** + * Selects a category in the category list based on the option value. + * + * @param categoryOptionValue the option value + */ + public void selectCategory(final String categoryOptionValue) { + setSelectValue(XpathSelector.CATEGORY_SELECT, categoryOptionValue); + } + + /** + * Selects the network package onboarding procedure option. + */ + public void selectNetworkPackageOnboardingProcedure() { + wrappingElement.findElement(By.xpath(METHOD_RADIO.getXpath())).click(); + } + + private void setInputValue(final XpathSelector inputTestId, final String value) { + findSubElement(wrappingElement, By.xpath(inputTestId.getXpath())).sendKeys(value); + } + + private void setSelectIndex(final XpathSelector inputTestId, final int index) { + new Select(findSubElement(wrappingElement, By.xpath(inputTestId.getXpath()))).selectByIndex(index); + } + + private void setSelectValue(final XpathSelector inputTestId, final String value) { + new Select(findSubElement(wrappingElement, By.xpath(inputTestId.getXpath()))).selectByValue(value); + } + + private void clickElement(final XpathSelector elementTestId) { + wrappingElement.findElement(By.xpath(elementTestId.getXpath())).click(); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + MODAL_XPATH("software-product-creation-page", "//div[@class='%s']"), + NAME_TXT("new-vsp-name", "//input[@data-test-id='%s']"), + VENDOR_SELECT("new-vsp-vendor", "//select[@data-test-id='%s']"), + CATEGORY_SELECT("new-vsp-category", "//select[@data-test-id='%s']"), + DESCRIPTION_TXT("new-vsp-description", "//textarea[@data-test-id='%s']"), + METHOD_RADIO("new-vsp-creation-procedure-heat", "//input[@data-test-id='%s']/parent::label"), + CREATE_BTN("form-submit-button", "//*[@data-test-id='%s']"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspRepositoryModalComponent.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspRepositoryModalComponent.java new file mode 100644 index 0000000000..75887fb7c4 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspRepositoryModalComponent.java @@ -0,0 +1,126 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.LoaderHelper; +import org.onap.sdc.frontend.ci.tests.utilities.NotificationHelper; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsNot.not; +import static org.junit.Assert.assertThat; +import static org.onap.sdc.frontend.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.IMPORT_VSP_BTN; +import static org.onap.sdc.frontend.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.MODAL_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.RESULTS_CONTAINER_DIV; +import static org.onap.sdc.frontend.ci.tests.pages.VspRepositoryModalComponent.XpathSelector.SEARCH_TXT; + +/** + * Handles the VSP Repository Modal UI actions + */ +public class VspRepositoryModalComponent extends AbstractPageObject { + + private static final Logger LOGGER = LoggerFactory.getLogger(VspRepositoryModalComponent.class); + + private WebElement wrappingElement; + + public VspRepositoryModalComponent(final WebDriver webDriver) { + super(webDriver); + timeoutInSeconds = 5; + } + + @Override + public void isLoaded() { + wrappingElement = getWrappingElement(); + GeneralUIUtils.ultimateWait(); + final List<WebElement> vspResultList = wrappingElement + .findElements(By.className(RESULTS_CONTAINER_DIV.getId())); + assertThat("VSP Repository should contain at least one result", vspResultList, is(not(empty()))); + } + + /** + * Clicks on the Import Vsp button of the given repository item position in the list. + * + * @param listPosition the position of the element in the VSP list, starting from 1 + * @return the next page object + */ + public ResourceCreatePage clickOnImportVsp(final int listPosition) { + final List<WebElement> vspResultList = + findSubElements(wrappingElement, By.className(RESULTS_CONTAINER_DIV.getId())); + vspResultList.get(listPosition).click(); + GeneralUIUtils.clickOnElementByTestId(IMPORT_VSP_BTN.getId()); + return new ResourceCreatePage(webDriver, new LoaderHelper(), new NotificationHelper()); + } + + /** + * Searches for a VSP in the repository list. + * + * @param vspName the VSP name to search + */ + public void searchForVSP(final String vspName) { + final WebElement searchTxtElement = findSubElement(wrappingElement, By.xpath(SEARCH_TXT.getXpath())); + searchTxtElement.sendKeys(vspName); + GeneralUIUtils.ultimateWait(); + } + + /** + * Gets the enclosing element of the modal. + * + * @return the enclosing element + */ + public WebElement getWrappingElement() { + LOGGER.debug("Finding element with xpath '{}'", MODAL_DIV.getXpath()); + return waitForElementVisibility(MODAL_DIV.getXpath()); + } + + /** + * Enum that contains identifiers and xpath expressions to elements related to the enclosing page object. + */ + public enum XpathSelector { + MODAL_DIV("importVspTable", "//*[@data-tests-id='%s']"), + SEARCH_TXT("onboarding-search-input", "//input[@data-tests-id='%s']"), + IMPORT_VSP_BTN("import-csar", "//*[@data-tests-id='%s']"), + RESULTS_CONTAINER_DIV("datatable-body-cell-label", "//datatable-body[contains(@class,'%s']"); + + private final String id; + private final String xpathFormat; + + XpathSelector(final String id, final String xpathFormat) { + this.id = id; + this.xpathFormat = xpathFormat; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpathFormat, id); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspValidationPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspValidationPage.java new file mode 100644 index 0000000000..6d980ceb64 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspValidationPage.java @@ -0,0 +1,135 @@ +/** + * Copyright (c) 2019 Vodafone Group + * + * 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. + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.apache.commons.collections.CollectionUtils; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import java.io.File; +import java.util.List; + +public class VspValidationPage extends GeneralPageElements { + + private VspValidationPage() { + super(); + } + + public static void navigateToVspValidationPageUsingNavbar() throws Exception { + clickOnElementUsingTestId(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_NAVBAR); + } + + public static void navigateToVspValidationPageUsingBreadcrumbs() throws Exception { + clickOnElementUsingTestId(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_BREADCRUMBS); + } + + public static void clickOnNextButton() throws Exception { + clickOnElementUsingTestId(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_PROCEED_TO_INPUTS_BUTTON); + } + + public static void clickOnBackButton() throws Exception { + clickOnElementUsingTestId(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_PROCEED_TO_SETUP_BUTTON); + } + + public static void clickOnSubmitButton() throws Exception { + clickOnElementUsingTestId(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_PROCEED_TO_RESULTS_BUTTON); + } + + public static void loadVSPFile(String path, String filename) { + List<WebElement> checkboxes = + GeneralUIUtils.findElementsByXpath("//div[@class='validation-input-wrapper']//input"); + boolean hasValue = CollectionUtils.isNotEmpty(checkboxes); + if (hasValue) { + WebElement browseWebElement = checkboxes.get(0); + browseWebElement.sendKeys(path + File.separator + filename); + GeneralUIUtils.ultimateWait(); + } else { + Assert.fail("Did not find File input field in the page for loading VSP test file"); + } + + } + public static boolean checkNextButtonDisabled() throws Exception { + return GeneralUIUtils.isElementDisabled(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_PROCEED_TO_INPUTS_BUTTON.getValue()); + } + + public static void clickCertificationQueryAll() throws Exception { + List<WebElement> checkboxes = GeneralUIUtils.findElementsByXpath("//div[@data-test-id='vsp-validation-certifications-query-checkbox-tree']//label//span[@class='rct-checkbox']"); + if (!checkboxes.isEmpty()) { + checkboxes.get(0).click(); + } else { + Assert.fail("Did not find certification test checkbox in the page"); + } + } + + public static void clickComplianceChecksAll() throws Exception { + List<WebElement> vnfComplianceCheckboxes = GeneralUIUtils.findElementsByXpath("//div[@data-test-id='vsp-validation-compliance-checks-checkbox-tree']//span[@class='rct-text' and .//label//text()='vnf-compliance']//button"); + if (!vnfComplianceCheckboxes.isEmpty()) { + vnfComplianceCheckboxes.get(vnfComplianceCheckboxes.size() - 1).click(); + } else { + Assert.fail("Did not find vnf-compliance test checkbox in the page"); + } + List<WebElement> checkboxes = GeneralUIUtils.findElementsByXpath("//div[@data-test-id='vsp-validation-compliance-checks-checkbox-tree']//label//span[@class='rct-title' and text()='csar-validate']"); + if (!checkboxes.isEmpty()) { + checkboxes.get(checkboxes.size() - 1).click(); + } else { + Assert.fail("Did not find csar-validate test Checkbox in the page"); + } + } + + public static boolean checkCertificationQueryExists() throws Exception { + WebElement parentDiv = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_CERTIFICATION_CHECKBOX_TREE.getValue()); + List<WebElement> checkboxTreeDivs = getChildElements(parentDiv); + List<WebElement> orderedList = getChildElements(checkboxTreeDivs.get(0)); + return (!orderedList.isEmpty()); + } + + public static boolean checkComplianceCheckExists() throws Exception { + WebElement parentDiv = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.VspValidationPage.VSP_VALIDATION_PAGE_COMPLIANCE_CHECKBOX_TREE.getValue()); + List<WebElement> checkboxTreeDivs = getChildElements(parentDiv); + List<WebElement> orderedList = getChildElements(checkboxTreeDivs.get(0)); + return (!orderedList.isEmpty()); + } + + public static boolean checkSelectedComplianceCheckExists() throws Exception { + WebElement selectedTests = GeneralUIUtils.findElementsByXpath("//div[contains(text(),'Selected Compliance Tests')]/..//select[@class='validation-setup-selected-tests']").get(0); + List<WebElement> options = getChildElements(selectedTests); + return (!options.isEmpty()); + } + + public static boolean checkSelectedCertificationQueryExists() throws Exception { + WebElement selectedTests = GeneralUIUtils.findElementsByXpath("//div[contains(text(),'Selected Certifications Query')]/..//select[@class='validation-setup-selected-tests']").get(0); + List<WebElement> options = getChildElements(selectedTests); + return (!options.isEmpty()); + } + + public static void clickOnElementUsingTestId(DataTestIdEnum.VspValidationPage elementTestId) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", elementTestId.name())); + GeneralUIUtils.getWebElementByTestID(elementTestId.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + + private static List<WebElement> getChildElements(WebElement webElement) throws Exception { + return webElement.findElements(By.xpath(".//*")); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspValidationResultsPage.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspValidationResultsPage.java new file mode 100644 index 0000000000..dc7c0fa421 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/pages/VspValidationResultsPage.java @@ -0,0 +1,51 @@ +/** + * Copyright (c) 2019 Vodafone Group + * + * 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. + */ + +package org.onap.sdc.frontend.ci.tests.pages; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class VspValidationResultsPage extends GeneralPageElements { + + private VspValidationResultsPage() { + super(); + } + + public static void navigateToVspValidationResultsPageUsingNavbar() throws Exception { + clickOnElementUsingTestId(DataTestIdEnum.VspValidationResultsPage.VSP_VALIDATION_RESULTS_PAGE_NAVBAR); + } + + public static void navigateToVspValidationResultsPageUsingBreadcrumbs() throws Exception { + clickOnElementUsingTestId(DataTestIdEnum.VspValidationResultsPage.VSP_VALIDATION_RESULTS_PAGE_BREADCRUMBS); + } + + public static boolean checkResultsExist() throws Exception { + List<WebElement> results = GeneralUIUtils.findElementsByXpath("//h4[contains(text(),'No Validation Checks Performed')]"); + return results.size() == 0; + } + + public static void clickOnElementUsingTestId(DataTestIdEnum.VspValidationResultsPage elementTestId) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", elementTestId.name())); + GeneralUIUtils.getWebElementByTestID(elementTestId.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/AdditionalConditions.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/AdditionalConditions.java new file mode 100644 index 0000000000..20ef579500 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/AdditionalConditions.java @@ -0,0 +1,105 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.paulhammant.ngwebdriver.NgWebDriver; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.support.ui.ExpectedCondition; + +public class AdditionalConditions { + + private AdditionalConditions() { + + } + + public static ExpectedCondition<Boolean> jQueryAJAXCallsHaveCompleted() { + return new ExpectedCondition<Boolean>() { + @Override + public Boolean apply(WebDriver driver) { + return (Boolean) ((JavascriptExecutor) driver). + executeScript("return (window.jQuery!= null) && (jQuery.active === 0);"); + } + }; + } + + public static ExpectedCondition<Boolean> angularHasFinishedProcessing() { + return new ExpectedCondition<Boolean>() { + @Override + public Boolean apply(WebDriver driver) { + new NgWebDriver((JavascriptExecutor) driver).waitForAngularRequestsToFinish(); + return true; + } + }; + } + + public static ExpectedCondition<Boolean> pageLoadWait() { + return new ExpectedCondition<Boolean>() { + @Override + public Boolean apply(WebDriver driver) { + String scriptJS = "try {\n" + + " if (document.readyState !== 'complete') {\r\n" + + " return false; // Page not loaded yet\r\n" + + " }\r\n" + + " if (window.jQuery) {\r\n" + + " if (window.jQuery.active) {\r\n" + + " return false;\r\n" + + " } else if (window.jQuery.ajax && window.jQuery.ajax.active) {\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " if (window.angular) {\r\n" + + " if (!window.qa) {\r\n" + + " // Used to track the render cycle finish after loading is complete\r\n" + + " window.qa = {\r\n" + + " doneRendering: false\r\n" + + " };\r\n" + + " }\r\n" + + " // Get the angular injector for this app (change element if necessary)\r\n" + + " var injector = window.angular.element('body').injector();\r\n" + + " // Store providers to use for these checks\r\n" + + " var $rootScope = injector.get('$rootScope');\r\n" + + " var $http = injector.get('$http');\r\n" + + " var $timeout = injector.get('$timeout');\r\n" + + " // Check if digest\r\n" + + " if ($rootScope.$$phase === '$apply' || $rootScope.$$phase === '$digest' || $http.pendingRequests.length !== 0) {\r\n" + + " window.qa.doneRendering = false;\r\n" + + " return false; // Angular digesting or loading data\r\n" + + " }\r\n" + + " if (!window.qa.doneRendering) {\r\n" + + " // Set timeout to mark angular rendering as finished\r\n" + + " $timeout(function() {\r\n" + + " window.qa.doneRendering = true;\r\n" + + " }, 0);\r\n" + + " return false;\r\n" + + " }\r\n" + + " }\r\n" + + " return true;\r\n" + + "} catch (ex) {\r\n" + + " return false;\r\n" + + "}"; + return Boolean.valueOf(((JavascriptExecutor) driver).executeScript(scriptJS).toString()); + } + }; + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/AdminWorkspaceUIUtilies.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/AdminWorkspaceUIUtilies.java new file mode 100644 index 0000000000..de5e0eef41 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/AdminWorkspaceUIUtilies.java @@ -0,0 +1,53 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import org.onap.sdc.frontend.ci.tests.pages.AdminGeneralPage; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; + +public class AdminWorkspaceUIUtilies { + + private AdminWorkspaceUIUtilies() { + + } + + public static void createNewUser(String userId, UserRoleEnum userRole) { + AdminGeneralPage.getUserManagementTab().setNewUserBox(userId); + AdminGeneralPage.getUserManagementTab().selectUserRole(userRole); + AdminGeneralPage.getUserManagementTab().clickCreateButton(); + } + + public static void updateUserRole(int rowIndx, UserRoleEnum userRole) { + AdminGeneralPage.getUserManagementTab().updateUser(rowIndx); + AdminGeneralPage.getUserManagementTab().updateUserRole(userRole, rowIndx); + AdminGeneralPage.getUserManagementTab().saveAfterUpdateUser(rowIndx); + } + + public static void deleteFirstRow() { + AdminGeneralPage.getUserManagementTab().deleteUser(0); + } + + public static void searchForUser(String searchString) { + AdminGeneralPage.getUserManagementTab().searchUser(searchString); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ArtifactUIUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ArtifactUIUtils.java new file mode 100644 index 0000000000..6722d41246 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ArtifactUIUtils.java @@ -0,0 +1,370 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition; +import org.onap.sdc.frontend.ci.tests.datatypes.ArtifactInfo; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.HeatWithParametersDefinition; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.InformationalArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.UploadArtifactPopup; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertTrue; + +public final class ArtifactUIUtils { + + private static final String PARAMETERS = "parameters"; + private static final String DATA_TESTS_ID = "//*[@data-tests-id='"; + + private ArtifactUIUtils() { + } + + public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo) throws Exception { + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(); + fillAndAddNewArtifactParameters(artifactInfo, artifactPopup); + } + + public static void fillAndAddNewArtifactParameters(ArtifactInfo artifactInfo, UploadArtifactPopup artifactPopup) throws Exception { + artifactPopup.defineArtifactLabel(artifactInfo.getArtifactLabel()); + artifactPopup.selectArtifactType(artifactInfo.getArtifactType()); + artifactPopup.insertDescription(artifactInfo.getDescription()); + artifactPopup.loadUndefinedFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); + artifactPopup.clickUpgradeArtifactsButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("A new artifact of type %s was added", artifactInfo.getArtifactType())); + } + + public static void fillAndAddNewEnvArtifactParameters(ArtifactInfo artifactInfo, UploadArtifactPopup artifactPopup) throws Exception { + artifactPopup.insertDescription(artifactInfo.getDescription()); + artifactPopup.loadFile(artifactInfo.getFilepath(), artifactInfo.getFilename()); + artifactPopup.clickDoneButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("ENV parameters %s artifact updated ", artifactInfo.getArtifactType())); + } + + public static void fillPlaceHolderInformationalArtifact(DataTestIdEnum.InformationalArtifactsPlaceholders artifactLabel, String filepath, String filename, String description) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + InformationalArtifactPage.artifactPopup().loadFile(filepath, filename); + InformationalArtifactPage.artifactPopup().insertDescription(description); + InformationalArtifactPage.artifactPopup().clickDoneButton(); + } + + public static void fillPlaceHolderInformationalArtifact(DataTestIdEnum.InformationalArtifactsService artifactLabel, + String filepath, String filename, String description) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filepath, filename); + artifactPopup.insertDescription(description); + artifactPopup.clickDoneButton(); + } + + public static void fillPlaceHolderAPIArtifact(DataTestIdEnum.APIArtifactsService artifactLabel, + String filepath, String filename, String description, String url) throws Exception { + GeneralUIUtils.clickOnElementByTestId(artifactLabel.getValue()); + UploadArtifactPopup artifactPopup = new UploadArtifactPopup(true); + artifactPopup.loadFile(filepath, filename); + artifactPopup.insertURL(url); + artifactPopup.insertDescription(description); + artifactPopup.clickDoneButton(); + } + + public static void validateArtifactNameVersionType(String artifactLabel, String artifactVersion, String artifactType) { + if (!GeneralUIUtils.getDriver().findElement(By.xpath(DATA_TESTS_ID + DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactLabel)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact label not equal - this warning represent defect."); + } + if (artifactVersion != null) { + if (!GeneralUIUtils.getDriver().findElement(By.xpath(DATA_TESTS_ID + DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactVersion)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact version not equal - this warning represent defect."); + } + } + if (artifactType != null) { + if (!GeneralUIUtils.getDriver().findElement(By.xpath(DATA_TESTS_ID + DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + artifactLabel + "']")).getAttribute("textContent").trim().equals(artifactType)) { + SetupCDTest.getExtendTest().log(Status.WARNING, "Artifact type not equal - this warning represent defect."); + } + } + } + + public static void validateExistArtifactOnDeploymentInformationPage(String expectedArtifactLabel, String artifactUUID, String artifactVersion, String artifactType, boolean isDownloadable, boolean isEditable, boolean isDeletable, boolean isArtifactParametersEditable) { + + String dataTestId = DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + expectedArtifactLabel; + + List<WebElement> artifactElements = GeneralUIUtils.getWebElementsListByContainTestID(dataTestId); + Assert.assertEquals(artifactElements.size(), 1, "There are more then one artifact named " + expectedArtifactLabel); + + WebElement artifact = artifactElements.get(0); + String actualArtifactLabel = GeneralUIUtils.getTextContentAttributeValue(artifact).trim(); + Assert.assertEquals(actualArtifactLabel, expectedArtifactLabel); + + if (artifactUUID != null) { + WebElement uuid = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.UUID.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(uuid).trim(), artifactUUID, "Artifact uuid not equal."); + } + if (artifactVersion != null) { + WebElement version = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.VERSION.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(version).trim(), artifactVersion, "Artifact version not equal."); + } + if (artifactType != null) { + WebElement type = GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.TYPE.getValue() + expectedArtifactLabel); + Assert.assertEquals(GeneralUIUtils.getTextContentAttributeValue(type).trim(), artifactType, "Artifact type not equal."); + } + if (isArtifactParametersEditable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that parameters edit button enabled."); + } else { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that parameters edit button disabled."); + } + if (isDownloadable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that download button enabled."); + } else { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that download button disabled."); + } + if (isEditable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that edit button enabled."); + } else { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.EDIT_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that edit button disabled."); + } + if (isDeletable) { + Assert.assertNotNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that delete button enabled."); + } else { + Assert.assertNull(GeneralUIUtils.getInputElement(DataTestIdEnum.ArtifactPageEnum.DELETE_ARTIFACT.getValue() + expectedArtifactLabel), "Expect that delete button disabled."); + } + } + + public static void validateNotExistArtifactOnDeploymentInformationPage(String artifactLabel) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPageEnum.ARTIFACT_NAME.getValue() + artifactLabel), false); + } + + public static void validateExistArtifactOnCompositionRightMenuDeploymentInformationPage(String fileName, String artifactDisplayedName, + boolean isUpdateable, boolean isParametersEditable, boolean isDownloadable, boolean isDeleteable) { + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_NAME.getValue() + artifactDisplayedName).getText(), fileName); + Assert.assertEquals(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName).getText(), artifactDisplayedName); + + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + + if (isParametersEditable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactDisplayedName), true, "Expect that parameters edit button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.EDIT_PARAMETERS_OF_ARTIFACT.getValue() + artifactDisplayedName), false, "Expect that parameters edit button disabled."); + } + if (isDownloadable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + artifactDisplayedName), true, "Expect that download button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DOWNLOAD.getValue() + artifactDisplayedName), false, "Expect that download button disabled."); + } + if (isDeleteable) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + artifactDisplayedName), true, "Expect that delete button enabled."); + } else { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.DELETE.getValue() + artifactDisplayedName), false, "Expect that delete button disabled."); + } + if (isUpdateable) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), true, "Expect that edit button enabled."); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + GeneralUIUtils.waitForElementInVisibilityByTestId(DataTestIdEnum.ArtifactPopup.DONE_BUTTON.getValue()); + } else { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_DISPLAY_NAME.getValue() + artifactDisplayedName); + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.ArtifactPopup.MODAL_WINDOW.getValue()), false, "Expect that edit button disabled."); + } + + } + + public static void validateNotExistArtifactOnCompositionRightMenuDeploymentInformationPage(String artifactDisplayedName) { + Assert.assertEquals(GeneralUIUtils.isWebElementExistByTestId(DataTestIdEnum.DeploymentArtifactCompositionRightMenu.ARTIFACT_NAME.getValue() + artifactDisplayedName), false); + } + + public static File verifyUpdatedEnvParameters(HeatWithParametersDefinition pairToUpdate, File updateEnvFile, String dataTestId) throws Exception { + GeneralUIUtils.hoverOnAreaByTestId(dataTestId); + return verifyUpdatedEnvParameters(pairToUpdate, updateEnvFile); + } + + public static File verifyUpdatedEnvParameters(HeatWithParametersDefinition pairToUpdate, File updateEnvFile) throws Exception { + + String heatDisplayName = pairToUpdate.getHeatArtifactDisplayName(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ArtifactPageEnum.DOWNLOAD_ARTIFACT_ENV.getValue() + heatDisplayName); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + + String pattern = PARAMETERS; + Map<String, Object> mapUpdetedEnvFile = FileHandling.parseYamlFileToMapByPattern(updateEnvFile, pattern); + Map<String, Object> mapDownloadedEnvFile = FileHandling.parseYamlFileToMapByPattern(latestFilefromDir, pattern); + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to check, that ENV file was updated ..."); + assertTrue("File" + latestFilefromDir.getName() + " contains different parameters number from expected file", mapDownloadedEnvFile.size() == mapUpdetedEnvFile.size()); + assertTrue("Updated file contains not updated parameters value", mapDownloadedEnvFile.entrySet().containsAll(mapUpdetedEnvFile.entrySet())); + return latestFilefromDir; + } + + /** + * compare heat env files by pattern ("parameters") + * + * @param expectedFile + * @param actualFile + * @param pattern + * @throws Exception + */ + public static void compareYamlFilesByPattern(File expectedFile, File actualFile, String pattern) throws Exception { + + Map<String, Object> mapExpectedFile = FileHandling.parseYamlFileToMapByPattern(expectedFile, pattern); + Map<String, Object> mapActualFile = FileHandling.parseYamlFileToMapByPattern(actualFile, pattern); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to compare file " + expectedFile.getName()); + assertTrue("File " + actualFile.getName() + " contains different parameters number from expected file", mapActualFile.size() == mapExpectedFile.size()); + assertTrue("File " + actualFile.getName() + " does not contains all expected parameters", mapActualFile.entrySet().containsAll(mapExpectedFile.entrySet())); + } + + public static void compareYamlParametersByPattern(Map<String, Object> mapExpectedProperties, File actualFileProperties, String pattern) throws Exception { + + Map<String, Object> mapActualFileProerties = FileHandling.parseYamlFileToMapByPattern(actualFileProperties, pattern); + SetupCDTest.getExtendTest().log(Status.INFO, "Going to compare files ..."); + assertTrue("Actual file contains different parameters number from expected file", mapActualFileProerties.size() == mapExpectedProperties.size()); + Map<String, Object> newMap = new HashMap<>(mapActualFileProerties); + assertTrue("Actual file does not contains all expected parameters", newMap.entrySet().containsAll(mapExpectedProperties.entrySet())); + } + + + public static File uploadCreatedUpdateParametersEnvFile(HeatWithParametersDefinition heatEnvDetails, String directoryPath) throws Exception { + //created env file to upload + File pathToEnvParametersFile = prepareEnvParametersFile(heatEnvDetails, directoryPath); + ArtifactInfo heatEnvArtifactInfo = new ArtifactInfo(directoryPath, heatEnvDetails.getHeatEnvLabel() + ".env", "heatEnvDesc", heatEnvDetails.getHeatEnvLabel(), heatEnvDetails.getHeatEnvArtifactType()); + ArtifactUIUtils.fillAndAddNewEnvArtifactParameters(heatEnvArtifactInfo, CompositionPage.artifactPopup()); + return pathToEnvParametersFile; + } + + public static File prepareEnvParametersFile(HeatWithParametersDefinition heatEnvDetails, String directoryPath) throws IOException { + File pathToEnvParametersFile = FileHandling.createEmptyFile(directoryPath + heatEnvDetails.getHeatEnvLabel() + ".env"); + //fill file + FileHandling.writeToFile(pathToEnvParametersFile, "parameters:", 0); + for (HeatParameterDataDefinition paramDefinition : heatEnvDetails.getHeatParameterDefinition()) { + Object data = getDataToWrite(paramDefinition); + FileHandling.writeToFile(pathToEnvParametersFile, data, 2); + } + + return pathToEnvParametersFile; + } + + public static Object getDataToWrite(HeatParameterDataDefinition paramDefinition) { + final int testNumberParameter = 666; + Object data = ""; + switch (paramDefinition.getType()) { + case "string": + String text = "\"string\""; + data = getFormatedData(paramDefinition.getName(), text); + break; + case "number": + data = getFormatedData(paramDefinition.getName(), testNumberParameter); + break; + case "json": + String jsonText = "{\"param1\":\"param1\", \"param2\":2}"; + data = getFormatedData(paramDefinition.getName(), jsonText); + break; + case "boolean": + if (paramDefinition.getCurrentValue().equals("true")) { + data = getFormatedData(paramDefinition.getName(), false); + } else { + data = getFormatedData(paramDefinition.getName(), true); + } + break; + case "comma_delimited_list": + String commaDelimitedListText = "127.0.0.10, 127.0.0.15, 127.0.0.20"; + data = getFormatedData(paramDefinition.getName(), commaDelimitedListText); + break; + default: + break; + } + return data; + } + + + public static Map<String, Object> getDataToWriteInUI(List<HeatParameterDataDefinition> paramDefinitionFromGetResourceResponse) { + final int testNumberParameter = 666; + Map<String, Object> newValuesToUpdateInUI = new HashMap<>(); + for (HeatParameterDataDefinition param : paramDefinitionFromGetResourceResponse) { + switch (param.getType()) { + + case "string": + String text = "string"; + newValuesToUpdateInUI.put(param.getName(), text); + break; + case "number": + newValuesToUpdateInUI.put(param.getName(), testNumberParameter); + break; + case "json": + String jsonText = "{\"param1\":\"param1\", \"param2\":2}"; + newValuesToUpdateInUI.put(param.getName(), jsonText); + break; + case "boolean": + if (param.getCurrentValue().equals(true)) { + newValuesToUpdateInUI.put(param.getName(), false); + } else { + newValuesToUpdateInUI.put(param.getName(), true); + } + break; + case "comma_delimited_list": + String commaDelimitedListText = "127.0.0.10, 127.0.0.15, 127.0.0.20"; + newValuesToUpdateInUI.put(param.getName(), commaDelimitedListText); + break; + default: + break; + + } + + } + return newValuesToUpdateInUI; + } + + public static Object getValue(HeatParameterDataDefinition param) { + String type = param.getType(); + Object result = null; + switch (type) { + case "string": + result = param.getCurrentValue(); + break; + case "number": + result = new Integer(param.getCurrentValue()); + break; + case "json": + result = param.getCurrentValue(); + break; + case "boolean": + result = new Boolean(param.getCurrentValue()); + break; + case "comma_delimited_list": + result = param.getCurrentValue(); + break; + default: + break; + } + return result; + } + + public static Object getFormatedData(String name, Object text) { + return name + ": " + text; + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/CatalogUIUtilitis.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/CatalogUIUtilitis.java new file mode 100644 index 0000000000..f407998e47 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/CatalogUIUtilitis.java @@ -0,0 +1,135 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.utils.rest.CatalogRestUtils; +import org.onap.sdc.frontend.ci.tests.datatypes.CheckBoxStatusEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.TypesEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.WebElement; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CatalogUIUtilitis { + + private CatalogUIUtilitis() { + + } + + public static void clickTopMenuButton(TopMenuButtonsEnum button) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s button ...", button.name())); + switch (button) { + case CATALOG: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + case HOME: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + case ON_BOARDING: + GeneralUIUtils.getWebElementByTestID(button.getButton()).click(); + break; + default: + break; + } + GeneralUIUtils.ultimateWait(); + } + + public static String catalogFilterTypeChecBox(TypesEnum enumtype) throws Exception { + String Type = enumtype.toString().toLowerCase(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s ...", Type)); + GeneralUIUtils.getWebElementByTestID(enumtype.getValue()).click(); + return Type; + } + + public static List<String> catalogFilterStatusChecBox(CheckBoxStatusEnum statusEnum) { + List<String> status = null; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s status", statusEnum.name())); + switch (statusEnum) { + case IN_DESIGN: + status = Arrays.asList("NOT_CERTIFIED_CHECKIN", "NOT_CERTIFIED_CHECKOUT"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).click(); + break; + case READY_FOR_TESTING: + status = Arrays.asList("READY_FOR_CERTIFICATION"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).click(); + break; + case IN_TESTING: + status = Arrays.asList("CERTIFICATION_IN_PROGRESS"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).click(); + break; + case CERTIFIED: + case DISTRIBUTED: + status = Arrays.asList("CERTIFIED"); + GeneralUIUtils.getWebElementByTestID(statusEnum.getValue()).click(); + break; + default: + break; + } + return status; + } + + // Get all Categories uniqueID .//The parent categories. + public static List<String> getCategories() throws IOException, JSONException { + List<String> allCategoriesList = new ArrayList<>(); + RestResponse allcategoriesJson = CatalogRestUtils.getAllCategoriesTowardsCatalogBe(); + JSONArray categories = new JSONArray(allcategoriesJson.getResponse()); + for (int i = 0; i < categories.length(); i++) { + String categoryname = (String) categories.getJSONObject(i).get("name"); + allCategoriesList.add(categoryname); + } + return allCategoriesList; + } + + public static WebElement clickOnUpperCategoryCheckbox() /*throws InterruptedException*/ { + WebElement categoryCheckbox = getCategoryCheckbox(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s category ...", categoryCheckbox.getText())); + categoryCheckbox.click(); + GeneralUIUtils.ultimateWait(); + return categoryCheckbox; + } + + public static WebElement getCategoryCheckbox() { + List<WebElement> categoryCheckboxes = GeneralUIUtils.getElementsByCSS("span[data-tests-id*='category']"); // get all categories and subcategories + return categoryCheckboxes.get(0); + } + + public static void clickOnLeftPanelElement(DataTestIdEnum.CatalogPageLeftPanelFilterTitle leftPanelElement) throws InterruptedException { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s", leftPanelElement.name())); + GeneralUIUtils.getElementsByCSS(leftPanelElement.getValue()).forEach(WebElement::click); + } + + public static WebElement catalogSearchBox(String searchText) { + WebElement searchBox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()); + searchBox.clear(); + searchBox.sendKeys(searchText); + return searchBox; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/DownloadManager.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/DownloadManager.java new file mode 100644 index 0000000000..7827ec305f --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/DownloadManager.java @@ -0,0 +1,69 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.WebElement; + +import java.util.List; + +public class DownloadManager { + + private DownloadManager() { + + } + + /** + * this method download csar file from VSP repository to default browser download directory + * + * @param vspName + * @throws Exception + */ + public static void downloadCsarByNameFromVSPRepository(String vspName, Boolean isDelete) throws Exception { + + if (isDelete) { + FileHandling.cleanCurrentDownloadDir(); + } + HomePage.showVspRepository(); + boolean vspFound = HomePage.searchForVSP(vspName); + if (vspFound) { + ExtentTestActions.log(Status.INFO, String.format("Going to downloading VSP %s", vspName)); + final List<WebElement> elementsFromTable = GeneralPageElements.getElementsFromTable(); + elementsFromTable.get(0).click(); + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.DOWNLOAD_CSAR.getValue()); + ExtentTestActions.log(Status.INFO, "Succeeded to downloaded CSAR file named " + vspName + " into folder " + SetupCDTest.getWindowTest().getDownloadDirectory()); + GeneralUIUtils.getElementsByCSS("div[class^='w-sdc-modal-close']").forEach(e -> e.click()); + GeneralUIUtils.ultimateWait(); + } + } + + + public static void downloadCsarByNameFromVSPRepository(String vspName, String vspId) throws Exception { + downloadCsarByNameFromVSPRepository(vspName, true); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/FileHandling.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/FileHandling.java new file mode 100644 index 0000000000..bb058e4fca --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/FileHandling.java @@ -0,0 +1,549 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import com.clearspring.analytics.util.Pair; +import org.apache.commons.io.FileUtils; +import org.onap.sdc.backend.ci.tests.config.Config; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils; +import org.openecomp.sdc.be.model.DataTypeDefinition; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openecomp.sdc.common.util.GeneralUtility; +import org.yaml.snakeyaml.Yaml; + +import java.io.BufferedOutputStream; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +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 = new HashMap<>(); + 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<String, Object> parseYamlFileToMapByPattern(File yamlFile, String pattern) throws Exception { + Map<?, ?> yamlFileToMap = FileHandling.parseYamlFile(yamlFile.toString()); + Map<String, Object> objectMap = getObjectMapByPattern(yamlFileToMap, pattern); + return objectMap; + } + + @SuppressWarnings("unchecked") + public static Map<String, Object> getObjectMapByPattern(Map<?, ?> parseUpdetedEnvFile, String pattern) { + Map<String, Object> objectMap = null; + + Object objectUpdetedEnvFile = parseUpdetedEnvFile.get(pattern); + if (objectUpdetedEnvFile instanceof HashMap) { + objectMap = (Map<String, Object>) objectUpdetedEnvFile; + } + return objectMap; + } + + + public static Map<String, DataTypeDefinition> parseDataTypesYaml(String filePath) throws Exception { + @SuppressWarnings("unchecked") + Map<String, DataTypeDefinition> dataTypesMap = (Map<String, DataTypeDefinition>) parseYamlFile(filePath); + return dataTypesMap; + } +// ------------------------------------------------------------------------------------------------- + + + /** + * @param folder, folder name under "Files" folder + * @return path to given folder from perspective of working directory or sdc-vnfs repository + */ + public static String getFilePath(String folder) { + String filepath = System.getProperty("filePath"); + boolean isFilePathEmptyOrNull = (filepath == null || filepath.isEmpty()); + + // return folder from perspective of working directory ( in general for nightly run from Linux, should already contain "Files" directory ) + return FileHandling.getBasePath() + "src/test/resources/Files" + File.separator + folder + File.separator; + } + + public static String getBasePath() { + return System.getProperty("user.dir") + File.separator; + } + + public static String getSdcVnfsPath() { + String vnfsPath = System.getProperty("vnfs.path"); + if (vnfsPath != null && !vnfsPath.isEmpty()) { + return vnfsPath; + } + return getBasePath() + Paths.get("..", "..", "sdc-vnfs").toString(); + } + + public static String getResourcesFilesPath() { + return getSdcVnfsPath() + File.separator + "ui-tests" + File.separator + "Files" + File.separator; + } + + public static String getCiFilesPath() { + return getBasePath() + "src" + File.separator + "test" + 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 String getUpdateVSPVnfRepositoryPath() { + return getFilePath("UpdateVSP"); + } + + 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<String> filenames = new ArrayList<String>(); + + 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<String> filterFileNamesListFromFolder(String filepath, String extension) { + try { + File dir = new File(filepath); + List<String> filenames = new ArrayList<String>(); + + 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()); + } + + filenames.removeAll(OnboardingUtils.excludeXnfList); + + 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<? extends ZipEntry> entries = zipFile.entries(); + + List<String> artifactNames = new ArrayList<String>(); + + while (entries.hasMoreElements()) { + ZipEntry nextElement = entries.nextElement(); + if (!nextElement.isDirectory()) { + if (!nextElement.getName().equals("MANIFEST.json")) { + String name = nextElement.getName(); + artifactNames.add(name); + } + } + } + zipFile.close(); + // convert list to array + return artifactNames.toArray(new String[0]); + } 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 List<String> 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 + */ + public static synchronized File getLastModifiedFileNameFromDir() throws Exception { + return getLastModifiedFileNameFromDir(SetupCDTest.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); + if (dir.exists()) { + try { + FileUtils.cleanDirectory(dir); + } catch (IllegalArgumentException e) { + System.out.println("Failed to clean " + dir); + } catch (IOException e) { + System.out.println("Failed to clean " + 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) { + SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + + public static synchronized void writeToFile(File pathToFile, Map<String, Pair<String, Object>> 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<String, Pair<String, Object>> 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) { + SetupCDTest.getExtendTest().log(Status.INFO, "Unable to write to flie " + pathToFile); + } + } + + public static void deleteLastDowloadedFiles(List<File> files) throws IOException { + for (File file : files) { + File fileToDelete = new File(Config.instance().getDownloadAutomationFolder() + file.getName()); + fileToDelete.delete(); + } + } + + public static void cleanCurrentDownloadDir() throws IOException { + try { + ExtentTestActions.log(Status.INFO, "Cleaning directory " + SetupCDTest.getWindowTest().getDownloadDirectory()); + System.gc(); + FileUtils.cleanDirectory(new File(SetupCDTest.getWindowTest().getDownloadDirectory())); + } catch (Exception e) { + + } + } + + public static boolean isFileDownloaded(String downloadPath, String fileName) { + File dir = new File(downloadPath); + File[] dir_contents = dir.listFiles(); + return Arrays.stream(dir_contents).anyMatch(file -> file.getName().equals(fileName)); + } + + 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(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.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(); + SetupCDTest.getExtendTest().log(Status.INFO, "Create file " + fileToCreate); + } catch (IOException e) { + SetupCDTest.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(); + SetupCDTest.getExtendTest().log(Status.INFO, "File " + file.getName() + "has been deleted"); + } else { + SetupCDTest.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<File> getHeatAndHeatEnvArtifactsFromZip(File directory, String[] okFileExtensions) { + + List<File> 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().replace("/", "\\" + 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 < dirs.length; ++i) { + currToken = dirs[i]; + if (!entry.isDirectory() && i == dirs.length - 1) { + extractFile(zipIn, filePath); + } else { + if (currPath.endsWith(File.separator)) { + currPath = currPath + currToken; + } else { + currPath = currPath + File.separator + currToken; + } +// if the entry is a directory, make the directory + File dir = new File(currPath); + dir.mkdir(); + } + } + zipIn.closeEntry(); + entry = zipIn.getNextEntry(); + } + zipIn.close(); + } + + private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = zipIn.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + } + + public static int getFileCountFromDefaulDownloadDirectory() { + return new File(SetupCDTest.getWindowTest().getDownloadDirectory()).listFiles().length; + } + + + public static String getKeyByValueFromPropertyFormatFile(String fullPath, String key) { + Properties prop = new Properties(); + InputStream input = null; + String value = null; + try { + input = new FileInputStream(fullPath); + prop.load(input); + value = (prop.getProperty(key)); + + } catch (IOException ex) { + ex.printStackTrace(); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + return value.replaceAll("\"", ""); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/GeneralUIUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/GeneralUIUtils.java new file mode 100644 index 0000000000..302edacacb --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/GeneralUIUtils.java @@ -0,0 +1,772 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import static org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest.getExtendTest; +import static org.testng.AssertJUnit.assertTrue; + +import com.aventstack.extentreports.Status; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import org.apache.commons.io.FileUtils; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.exception.GeneralUiRuntimeException; +import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.backend.ci.tests.utils.Utils; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.Keys; +import org.openqa.selenium.NoSuchElementException; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.interactions.Actions; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public final class GeneralUIUtils { + + private static final Logger LOGGER = LoggerFactory.getLogger(GeneralUIUtils.class); + + private static final String TEST_ID_XPATH = "//*[@data-test-id='%1$s' or @data-tests-id='%1$s']"; + private static final String TEST_ID_CHILD_XPATH = "//*[@data-tests-id='%s']//*"; + private static final String TEST_ID_ATTRIBUTE_NAME = "data-tests-id"; + private static final String COLOR_YELLOW_BORDER_4PX_SOLID_YELLOW = "color: yellow; border: 4px solid yellow;"; + + private static final int TIME_OUT = (int) (60 * 1.5); + private static final int WEB_DRIVER_WAIT_TIME_OUT = 10; + private static final int SLEEP_DURATION = 1000; + private static final int MAX_WAITING_PERIOD = 10 * 1000; + private static final int NAP_PERIOD = 100; + private static final int DURATION_FORMATIN = 60; + + private GeneralUIUtils () { + + } + + public static int getTimeOut() { + return TIME_OUT; + } + + public static WebDriver getDriver() { + return DriverFactory.getDriver(); + } + + public static List<WebElement> getElementsByLocator(By by) { + return getDriver().findElements(by); + } + + public static File takeScreenshot(String screenshotFilename, String dir, String testName) throws IOException { + if (screenshotFilename == null) { + if (testName != null) { + screenshotFilename = testName; + } else { + screenshotFilename = UUID.randomUUID().toString(); + } + } + try { + File scrFile = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.FILE); + File filePath = new File(String.format("%s/%s.png", dir, screenshotFilename)); + new File(dir).mkdirs(); + FileUtils.copyFile(scrFile, filePath); + return filePath; + } catch (IOException e1) { + e1.printStackTrace(); + } + return null; + } + + public static File takeScreenshot(String screenshotFilename, String dir) throws IOException { + return takeScreenshot(screenshotFilename, dir, null); + } + + public static WebElement getWebElementByTestID(String dataTestId) { + return getWebElementByTestID(dataTestId, TIME_OUT); + } + + public static WebElement getWebElementByTestID(final String dataTestId, final int timeout) { + try { + final WebDriverWait wait = new WebDriverWait(getDriver(), timeout); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))); + } + catch (final Exception e) { + LOGGER + .debug(String.format("Element with attribute %s=%s not found", TEST_ID_ATTRIBUTE_NAME, dataTestId), e); + } + return null; + } + + public static boolean isWebElementExistByTestId(String dataTestId) { + return getDriver().findElements(By.xpath(String.format(TEST_ID_XPATH, dataTestId))).size() != 0; + } + + public static boolean isWebElementExistByClass(String className) { + return getDriver().findElements(By.className(className)).size() != 0; + } + + public static WebElement getInputElement(String dataTestId) { + try { + ultimateWait(); + return getDriver().findElement(By.xpath(String.format(TEST_ID_XPATH, dataTestId))); + } catch (Exception e) { + return null; + } + } + + public static List<WebElement> getInputElements(String dataTestId) { + ultimateWait(); + return getDriver().findElements(By.xpath(String.format(TEST_ID_XPATH, dataTestId))); + + } + + public static WebElement getWebElementBy(By by) { + return getWebElementBy(by, TIME_OUT); + } + + public static WebElement getWebElementBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfElementLocated(by)); + } + + public static WebElement getWebElementByPresence(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.presenceOfElementLocated(by)); + } + + public static List<String> getWebElementListText(List<WebElement> elements) { + List<String> Text = new ArrayList<>(); + for (WebElement webElement : elements) { + Text.add(webElement.getText()); + } + return Text; + } + + public static List<WebElement> getWebElementsListBy(By by) { + return getWebElementsListBy(by, TIME_OUT); + } + + public static List<WebElement> getWebElementsListBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(by)); + } + + public static List<WebElement> getWebElementsListByContainTestID(final String dataTestId) { + try { + final WebDriverWait wait = new WebDriverWait(getDriver(), WEB_DRIVER_WAIT_TIME_OUT); + final String xpath = String.format("//*[contains(@%s, '%s')]", TEST_ID_ATTRIBUTE_NAME, dataTestId); + return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(xpath))); + } catch (final Exception e) { + final String message = String.format("Could not find element containing the attribute '%s' as '%s'", + TEST_ID_ATTRIBUTE_NAME, dataTestId); + LOGGER.debug(message, e); + return Collections.emptyList(); + } + } + + public static List<WebElement> getWebElementsListByContainsClassName(final String containedText) { + final WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions. + presenceOfAllElementsLocatedBy(By.xpath(String.format("//*[contains(@class, '%s')]", containedText)))); + } + + public static WebElement getWebElementByContainsClassName(final String containedText) { + return getWebElementBy(By.xpath(String.format("//*[contains(@class, '%s')]", containedText))); + } + + public static WebElement getWebElementByClassName(String className) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.className(className))); + } + + public static List<WebElement> getWebElementsListByTestID(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))); + } + + public static List<WebElement> getWebElementsListByClassName(String className) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.className(className))); + } + + + public static Boolean isElementInvisibleByTestId(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))); + } + + public static Boolean isElementVisibleByTestId(String dataTestId) { + try { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath(String.format(TEST_ID_XPATH, dataTestId))))).isDisplayed(); + } catch (Exception e) { + return false; + } + } + + public static void clickOnElementByTestId(String dataTestId) { + try { + clickOnElementByTestIdWithoutWait(dataTestId); + ultimateWait(); + }catch (Exception e) { + LOGGER.debug("", e); + } + } + + public static void clickOnElementByTestIdWithoutWait(final String dataTestId) { + try { + final WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + wait.until(ExpectedConditions + .elementToBeClickable(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))).click(); + final String message = + String.format("Click on element with attribute '%s' value '%s'", TEST_ID_XPATH, dataTestId); + getExtendTest().log(Status.INFO, message); + } catch (final Exception e) { + ExtentTestActions.log(Status.FAIL, dataTestId + " element isn't clickable"); + ExtentTestActions.log(Status.FAIL, e); + } + } + + public static void clickOnElementByInputTestIdWithoutWait(final String dataTestId) { + final WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + final String xPath = String.format(TEST_ID_CHILD_XPATH, dataTestId); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath(xPath))).click(); + } + + public static void clickOnElementByTestId(String dataTestId, int customTimeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), customTimeout); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))).click(); + } + + public static WebElement waitForElementVisibilityByTestId(String dataTestId) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + return wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId) { + return waitForElementInVisibilityByTestId(dataTestId, TIME_OUT); + } + + public static Boolean waitForElementInVisibilityByTestId(String dataTestId, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + boolean displayed = getDriver().findElements(By.xpath(String.format(TEST_ID_XPATH, dataTestId))).isEmpty(); + if (!displayed) { + return wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))); + } + return false; + } + + public static Boolean waitForElementInVisibilityByTestId(By by) { + return waitForElementInVisibilityBy(by, TIME_OUT); + } + + + public static Boolean waitForElementInVisibilityBy(By by, int timeOut) { + WebDriverWait wait = new WebDriverWait(getDriver(), timeOut); + boolean displayed = getDriver().findElements(by).isEmpty(); + if (!displayed) { + Boolean until = wait.until(ExpectedConditions.invisibilityOfElementLocated(by)); + sleep(SLEEP_DURATION); + return until; + } + return false; + } + + + public static void setWebElementByTestId(String elemetID, String value) { + WebElement resourceDescriptionTextbox = GeneralUIUtils.getWebElementByTestID(elemetID); + resourceDescriptionTextbox.clear(); + resourceDescriptionTextbox.sendKeys(value); + + } + + public static WebElement hoverAndClickOnButtonByTestId(String areaId,String buttonId) { + Actions actions = new Actions(getDriver()); + //WebElement area = getInputElement(areaId); + //actions.moveToElement(area).build().perform(); + //actions.moveToElement(area).moveToElement(getInputElement(buttonId)).click().build().perform(); + ((JavascriptExecutor)getDriver()).executeScript("arguments[0].style.visibility = 'visible';", getInputElement(buttonId)); + ((JavascriptExecutor)getDriver()).executeScript("arguments[0].click();", getInputElement(buttonId)); + //actions.moveToElement(getInputElement(buttonId)).click().build().perform(); + ultimateWait(); + return null; + } + + public static WebElement hoverOnAreaByTestId(String areaId) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByTestID(areaId); + actions.moveToElement(area).build().perform(); + ultimateWait(); + return area; + } + + public static WebElement hoverOnAreaByClassName(String className) { + Actions actions = new Actions(getDriver()); + WebElement area = getWebElementByClassName(className); + actions.moveToElement(area).build().perform(); + GeneralUIUtils.ultimateWait(); + return area; + } + + public static void waitForLoader() { + waitForLoader(TIME_OUT); + } + + public static void waitForLoader(int timeOut) { + final String loaderClass = "tlv-loader"; + final int sleepDuration = 500; + sleep(sleepDuration); + LOGGER.debug("Waiting {}s for '.{}'", timeOut, loaderClass); + waitForElementInVisibilityBy(By.className(loaderClass), timeOut); + } + + public static void findComponentAndClick(final String resourceName) { + HomePage.findComponentAndClick(resourceName); + } + + public static void windowZoomOut() { + final int zoomOutFactor = 3; + for (int i = 0; i < zoomOutFactor; i++) { + if (getDriver() instanceof FirefoxDriver) { + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT)); + } + } + } + + public static void resetZoom() { + getDriver().findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, "0")); + } + + public static void windowZoomOutUltimate() { + resetZoom(); + windowZoomOut(); + } + + public static void sleep(int duration) { + try { + Thread.sleep(duration); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + throw new GeneralUiRuntimeException("The thread was interrupted during a sleep", e); + } + } + + public static void moveToStep(final DataTestIdEnum.StepsEnum stepName) { + getExtendTest().log(Status.INFO, String.format("Going to %s page ", stepName.toString())); + moveToStep(stepName.getValue()); + } + + public static void moveToStep(final String dataTestId) { + clickOnElementByTestId(dataTestId); + } + + + public static Select getSelectList(String item, String datatestsid) { + Select selectList = new Select(getWebElementByTestID(datatestsid)); + if (item != null) { + selectList.selectByVisibleText(item); + } + return selectList; + } + + public static List<WebElement> getElementsByCSS(String cssString) /*throws InterruptedException*/ { + GeneralUIUtils.waitForLoader(); + return getDriver().findElements(By.cssSelector(cssString)); + } + + public static WebElement getElementfromElementByCSS(WebElement parentElement, String cssString) { + GeneralUIUtils.waitForLoader(); + return parentElement.findElement(By.cssSelector(cssString)); + } + + private static WebElement highlightMyElement(WebElement element) { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + javascript.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, COLOR_YELLOW_BORDER_4PX_SOLID_YELLOW); + return element; + } + + public static WebElement getSelectedElementFromDropDown(String dataTestId) { + GeneralUIUtils.ultimateWait(); + return new Select(getDriver().findElement(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))).getFirstSelectedOption(); + } + + public static Select getElementFromDropDown(String dataTestId) { + GeneralUIUtils.ultimateWait(); + return new Select(getDriver().findElement(By.xpath(String.format(TEST_ID_XPATH, dataTestId)))); + } + + public static boolean checkElementsCountInTable(int expectedElementsCount, Supplier<List<WebElement>> func) { + int maxWaitingPeriodMS = MAX_WAITING_PERIOD; + int napPeriodMS = NAP_PERIOD; + int sumOfWaiting = 0; + List<WebElement> elements; + boolean isKeepWaiting = false; + while (!isKeepWaiting) { + elements = func.get(); + isKeepWaiting = (expectedElementsCount == elements.size()); + sleep(napPeriodMS); + sumOfWaiting += napPeriodMS; + if (sumOfWaiting > maxWaitingPeriodMS) { + return false; + } + } + return true; + } + + public static String getActionDuration(Runnable func) { + long startTime = System.nanoTime(); + func.run(); + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); + return String.format("%02d:%02d", duration / DURATION_FORMATIN, duration % DURATION_FORMATIN); + } + + public static WebElement clickOnAreaJS(String areaId) { + return clickOnAreaJS(areaId, TIME_OUT); + } + + + public static WebElement clickOnAreaJS(String areaId, int timeout) { + try { + ultimateWait(); + WebElement area = getWebElementByTestID(areaId); + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + Object executeScript = javascript.executeScript("arguments[0].click();", area, COLOR_YELLOW_BORDER_4PX_SOLID_YELLOW); + waitForLoader(timeout); + ultimateWait(); + return area; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + public static WebElement clickOnAreaJS(WebElement areaId) throws InterruptedException { + JavascriptExecutor javascript = (JavascriptExecutor) getDriver(); + javascript.executeScript("arguments[0].click();", areaId, COLOR_YELLOW_BORDER_4PX_SOLID_YELLOW); + return areaId; + } + + + public static void clickSomewhereOnPage() { + getDriver().findElement(By.cssSelector(".asdc-app-title")).click(); + } + + public static void clickOnElementByText(String textInElement) { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + highlightMyElement(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))).click(); + } + + public static void clickOnElementByText(String textInElement, int customTimeout) { + WebDriverWait wait = new WebDriverWait(getDriver(), customTimeout); + highlightMyElement(wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement)))).click(); + } + + public static void clickJSOnElementByText(String textInElement) throws Exception { + //TODO SEB + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + //clickOnAreaJS(wait.until(ExpectedConditions.elementToBeClickable(findByText(textInElement)))); + wait.until( + ExpectedConditions.elementToBeClickable(findByText(textInElement))).click(); + } + + public static void waitForAngular() { + LOGGER.debug("Waiting for angular"); + final int webDriverWaitingTime = 90; + WebDriverWait wait = new WebDriverWait(getDriver(), webDriverWaitingTime, NAP_PERIOD); + wait.until(AdditionalConditions.pageLoadWait()); + wait.until(AdditionalConditions.angularHasFinishedProcessing()); + LOGGER.debug("Waiting for angular finished"); + } + + public static Object getAllElementAttributes(WebElement element) { + return ((JavascriptExecutor) getDriver()).executeScript("var s = []; var attrs = arguments[0].attributes; for (var l = 0; l < attrs.length; ++l) { var a = attrs[l]; s.push(a.name + ':' + a.value); } ; return s;", element); + } + + public static boolean isElementReadOnly(WebElement element) { + try { + highlightMyElement(element).clear(); + return false; + } catch (Exception e) { + return true; + } + } + + public static boolean isElementReadOnly(String dataTestId) { + return isElementReadOnly( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static boolean isElementDisabled(WebElement element) { + return highlightMyElement(element).getAttribute("class").contains("view-mode") + || element.getAttribute("class").contains("disabled") || element.getAttribute("disabled") != null; + } + + public static boolean isElementDisabled(String dataTestId) { + return isElementDisabled( + waitForElementVisibilityByTestId(dataTestId)); + } + + public static void ultimateWait() { + long startTime = System.nanoTime(); + + GeneralUIUtils.waitForLoader(); + GeneralUIUtils.waitForBackLoader(); + GeneralUIUtils.waitForAngular(); + + long estimateTime = System.nanoTime(); + long duration = TimeUnit.NANOSECONDS.toSeconds(estimateTime - startTime); + if (duration > TIME_OUT) { + getExtendTest().log(Status.WARNING, String.format("Delays on page, %d seconds", duration)); + } + } + + public static WebElement unhideElement(WebElement element, String attributeValue) { + String js = "arguments[0].setAttribute('class','" + attributeValue + "');"; + ((JavascriptExecutor) getDriver()).executeScript(js, element); + return element; + } + + public static WebElement findByText(String textInElement) { + return getDriver().findElement(searchByTextContaining(textInElement)); + } + + public static By searchByTextContaining(String textInElement) { + return By.xpath("//*[contains(text(),'" + textInElement + "')]"); + } + + public static WebElement getClickableButtonBy(By by, int timout) { + try { + WebDriverWait wait = new WebDriverWait(getDriver(), timout); + return wait.until(ExpectedConditions.elementToBeClickable(by)); + } catch (Exception e) { + return null; + } + } + + + public static WebElement getButtonWithText(String textInButton) { + try { + return getDriver().findElement(By.xpath("//button[contains(text(),'" + textInButton + "')]")); + } catch (Exception e) { + return null; + } + } + + public static void closeErrorMessage() { + WebElement okWebElement = getButtonWithText("OK"); + if (okWebElement != null) { + okWebElement.click(); + ultimateWait(); + } + } + + public static WebElement getElementByCSS(String cssString) throws InterruptedException { + ultimateWait(); + return getDriver().findElement(By.cssSelector(cssString)); + } + + public static String getDataTestIdAttributeValue(WebElement element) { + return element.getAttribute(TEST_ID_ATTRIBUTE_NAME); + } + + public static String getTextContentAttributeValue(WebElement element) { + return element.getAttribute("textContent"); + } + + public static void clickOnElementByCSS(String cssString) throws Exception { + WebDriverWait wait = new WebDriverWait(getDriver(), TIME_OUT); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(cssString))).click(); + ultimateWait(); + } + + public static boolean checkForDisabledAttribute(String dataTestId) { + Object elementAttributes = getAllElementAttributes(waitForElementVisibilityByTestId(dataTestId)); + return elementAttributes.toString().contains("disabled"); + } + + public static void dragAndDropElementByY(WebElement area, int yOffset) { + final int dragAndDropTimeout = 10; + Actions actions = new Actions(getDriver()); + actions.dragAndDropBy(area, dragAndDropTimeout, yOffset).build().perform(); + ultimateWait(); + } + + public static void waitForBackLoader() { + waitForBackLoader(TIME_OUT); + } + + public static void waitForBackLoader(int timeOut) { + sleep(NAP_PERIOD); + final String backLoaderClass = "tlv-loader-back"; + LOGGER.debug("Waiting {}s for '.{}'", timeOut, backLoaderClass); + waitForElementInVisibilityBy(By.className(backLoaderClass), timeOut); + } + + public static void addStringtoClipboard(String text) { + StringSelection selection = new StringSelection(text); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(selection, selection); + } + + public static boolean checkForDisabledAttributeInHiddenElement(String cssString) { + final int numberOfDisableElements = 3; + boolean isDisabled = false; + for (int i = 0; i < numberOfDisableElements; i++) { + Object elementAttributes = getAllElementAttributes(getWebElementByPresence(By.cssSelector(cssString), TIME_OUT)); + isDisabled = elementAttributes.toString().contains("disabled"); + if (isDisabled) { + break; + } + ultimateWait(); + } + return isDisabled; + } + + public static void selectByValueTextContained(String dataTestsId, String value) { + + List<WebElement> options = GeneralUIUtils.getWebElementsListBy(By.xpath(String.format("//select[@data-tests-id='%1$s' or @data-test-id='%1$s']//option[contains(@value,'%2$s')]", dataTestsId, value))); + + boolean matched = false; + for (WebElement option : options) { + option.click(); + matched = true; + } + + if (!matched) { + throw new NoSuchElementException("Cannot locate option with value: " + value); + } + + ultimateWait(); + } + + public static void setTextInElementByXpath(String xPath, String text) { + WebElement webElement = GeneralUIUtils.getWebElementBy(By.xpath(xPath)); + webElement.clear(); + webElement.click(); + webElement.sendKeys(text); + ultimateWait(); + } + + + public static void clickOnElementByXpath(String xPath) { + WebElement webElement = GeneralUIUtils.getWebElementBy(By.xpath(xPath)); + webElement.click(); + ultimateWait(); + } + + public static String getTextValueFromWebElementByXpath(String xpath) { + WebElement webElement = getWebElementBy(By.xpath(xpath)); + return webElement.getAttribute("value"); + } + + public static List<WebElement> findElementsByXpath(String xPath) { + return getDriver().findElements(By.xpath(xPath)); + } + + public static void clickOnBrowserBackButton() throws Exception { + getExtendTest().log(Status.INFO, "Going to press on back browser button."); + getDriver().navigate().back(); + ultimateWait(); + } + + public static String copyCurrentURL() throws Exception { + getExtendTest().log(Status.INFO, "Copying current URL"); + return getDriver().getCurrentUrl(); + } + + public static void navigateToURL(String url) throws Exception { + getExtendTest().log(Status.INFO, "Navigating to URL " + url); + getDriver().navigate().to(url); + } + + public static void refreshWebpage() throws Exception { + getExtendTest().log(Status.INFO, "Refreshing Webpage"); + getDriver().navigate().refresh(); + ultimateWait(); + } + + public static Object getElementPositionOnCanvas(String elementName) { + String scriptJS = "var cy = window.jQuery('.sdc-composition-graph-wrapper').cytoscape('get');\n" + + "var n = cy.nodes('[name=\"" + elementName + "\"]');\n" + + "var nPos = n.renderedPosition();\n" + + "return JSON.stringify({\n" + + "\tx: nPos.x,\n" + + "\ty: nPos.y\n" + + "})"; + return ((JavascriptExecutor) getDriver()).executeScript(scriptJS); + } + + public static Object getElementGreenDotPositionOnCanvas(String elementName) { + String scriptJS = "var cy = window.jQuery('.sdc-composition-graph-wrapper').cytoscape('get');\n" + + "var cyZoom = cy.zoom();\n" + + "var n = cy.nodes('[name=\"" + elementName + "\"]');\n" + + "var nPos = n.renderedPosition();\n" + + "var nData = n.data();\n" + + "var nImgSize = nData.imgWidth;\n" + + "var shiftSize = (nImgSize-18)*cyZoom/2;\n" + + "return JSON.stringify({\n" + + "\tx: nPos.x + shiftSize,\n" + + "\ty: nPos.y - shiftSize\n" + + "});"; + return ((JavascriptExecutor) getDriver()).executeScript(scriptJS); + } + + public static Long getAndValidateActionDuration(Runnable action, int regularTestRunTime) { + Long actualTestRunTime = null; + try { + actualTestRunTime = Utils.getActionDuration(() -> { + try { + action.run(); + } catch (Throwable throwable) { + throwable.printStackTrace(); + } + }); + } catch (Exception e) { + e.printStackTrace(); + } + final double factor = 1.5; + + assertTrue("Expected test run time should be less than " + regularTestRunTime * factor + ", " + + "actual time is " + actualTestRunTime, regularTestRunTime * factor > actualTestRunTime); + //SetupCDTest.getExtendTest().log(Status.INFO, "Actual catalog loading time is " + actualTestRunTime + " seconds"); + return actualTestRunTime; + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/HomeUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/HomeUtils.java new file mode 100644 index 0000000000..562dcb46db --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/HomeUtils.java @@ -0,0 +1,102 @@ +/*-
+ * ============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.onap.sdc.frontend.ci.tests.utilities;
+
+import com.aventstack.extentreports.Status;
+import org.onap.sdc.frontend.ci.tests.datatypes.CreateAndImportButtonsEnum;
+import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum;
+import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest;
+import org.openqa.selenium.By;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
+import org.testng.Assert;
+
+import java.util.List;
+
+public final class HomeUtils {
+
+ public static WebElement createAndImportButtons(CreateAndImportButtonsEnum type, WebDriver driver)
+ throws InterruptedException {
+ switch (type) {
+ case IMPORT_CP:
+ case IMPORT_VFC:
+ case IMPORT_VL:
+ case IMPORT_VF:
+ GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.IMPORT_AREA.getValue());
+ return GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.IMPORT_VFC.getValue());
+ case CREATE_SERVICE:
+ GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue());
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click();
+ break;
+
+ case CREATE_PRODUCT:
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click();
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click();
+ break;
+
+ default:
+ GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue());
+ driver.findElement(By.xpath("//*[@data-tests-id='createResourceButton']")).click();
+ break;
+ }
+ return null;
+
+ }
+
+ public static void findComponentAndClick(String componentName) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, "finding component " + componentName);
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName);
+ WebElement foundComp = null;
+ try {
+ foundComp = GeneralUIUtils.getWebElementByTestID(componentName);
+ foundComp.click();
+ GeneralUIUtils.waitForLoader();
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.LIFECYCLE_STATE.getValue());
+ } catch (Exception e) {
+ String msg = String.format("DID NOT FIND A COMPONENT NAMED %s", componentName);
+ SetupCDTest.getExtendTest().log(Status.FAIL, msg);
+ System.out.println(msg);
+ Assert.fail(msg);
+ }
+ }
+
+ public static void findComponentAndClickByVersion(String componentName, String version) throws Exception {
+ SetupCDTest.getExtendTest().log(Status.INFO, String.format("finding component %s v%s", componentName, version));
+ GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.MainMenuButtons.SEARCH_BOX.getValue()).sendKeys(componentName);
+ List<WebElement> foundComp = null;
+ try {
+ foundComp = GeneralUIUtils.getWebElementsListByTestID(componentName + "Version");
+
+ for (WebElement webElement : foundComp) {
+ if (webElement.getText().contains(version)) {
+ webElement.click();
+ GeneralUIUtils.ultimateWait();
+ break;
+ }
+ }
+ } catch (Exception e) {
+ String msg = String.format("DID NOT FIND A COMPONENT NAMED %s", componentName);
+ SetupCDTest.getExtendTest().log(Status.FAIL, msg);
+ System.out.println(msg);
+ Assert.fail(msg);
+ }
+ }
+}
diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/LoaderHelper.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/LoaderHelper.java new file mode 100644 index 0000000000..0170fbf074 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/LoaderHelper.java @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.utilities; + +import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory; +import org.openqa.selenium.By; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +public class LoaderHelper { + + private final By locator = By.className("tlv-loader"); + + public void waitForLoader(final int timeout) { + waitForLoaderVisibility(5); + waitForLoaderInvisibility(timeout); + } + + private void waitForLoaderVisibility(final int timeout) { + getWait(timeout) + .until(ExpectedConditions.visibilityOfElementLocated(locator)); + } + + private void waitForLoaderInvisibility(int timeout) { + getWait(timeout).until(ExpectedConditions.invisibilityOfElementLocated(locator)); + } + + private WebDriverWait getWait(final int timeout) { + return new WebDriverWait(DriverFactory.getDriver(), timeout); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/NotificationHelper.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/NotificationHelper.java new file mode 100644 index 0000000000..46d5c646bf --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/NotificationHelper.java @@ -0,0 +1,96 @@ +/* + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Nordix Foundation + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.sdc.frontend.ci.tests.utilities; + +import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory; +import org.openqa.selenium.By; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static org.onap.sdc.frontend.ci.tests.utilities.NotificationHelper.XpathSelector.MAIN_CONTAINER_DIV; +import static org.onap.sdc.frontend.ci.tests.utilities.NotificationHelper.XpathSelector.MESSAGE_CONTENT_DIV; +import static org.onap.sdc.frontend.ci.tests.utilities.NotificationHelper.XpathSelector.MESSAGE_SUCCESS_DIV; + +public class NotificationHelper { + + private static final Logger LOGGER = LoggerFactory.getLogger(NotificationHelper.class); + + public void waitForNotification(final NotificationType notificationType, final int timeout) { + final By messageLocator = getMessageLocator(notificationType); + waitForVisibility(messageLocator, timeout); + waitForInvisibility(messageLocator, timeout); + } + + private By getMessageLocator(final NotificationType notificationType) { + return By.xpath(getMessageXpath(notificationType)); + } + + private String getMessageXpath(final NotificationType notificationType) { + if (notificationType == NotificationType.SUCCESS) { + return String.format("%s%s%s", MAIN_CONTAINER_DIV.getXpath(), MESSAGE_CONTENT_DIV.getXpath(), MESSAGE_SUCCESS_DIV.getXpath()); + } + + LOGGER.warn("Xpath for NotificationType {} not yet implemented. Returning empty Xpath.", notificationType); + return ""; + } + + private void waitForVisibility(By messageLocator, final int timeout) { + getWait(timeout) + .until(ExpectedConditions.visibilityOfElementLocated(messageLocator)); + } + + private void waitForInvisibility(By messageLocator, int timeout) { + getWait(timeout) + .until(ExpectedConditions.invisibilityOfElementLocated(messageLocator)); + } + + private WebDriverWait getWait(final int timeout) { + return new WebDriverWait(DriverFactory.getDriver(), timeout); + } + + public enum XpathSelector { + MAIN_CONTAINER_DIV("notification-container", "//div[@class='%s']"), + MESSAGE_CONTENT_DIV("msg-content", "//div[@class='%s']"), + MESSAGE_SUCCESS_DIV("message", "//div[contains(@class, '%s') and contains(text(),'successfully')]"); + + private final String id; + private final String xpath; + + XpathSelector(String id, String xpath) { + this.id = id; + this.xpath = xpath; + } + + public String getId() { + return id; + } + + public String getXpath() { + return String.format(xpath, id); + } + } + + public enum NotificationType { + SUCCESS; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/OnboardingUiUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/OnboardingUiUtils.java new file mode 100644 index 0000000000..b415192697 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/OnboardingUiUtils.java @@ -0,0 +1,210 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.execute.devCI.ArtifactFromCsar; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentArtifactPage; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.HomePage; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; +import org.onap.sdc.frontend.ci.tests.verificator.VfVerificator; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ArtifactsCorrelationManager; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import java.io.File; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + + +public class OnboardingUiUtils { + + private static final int WAITING_FOR_LOADER_TIME_OUT = 60 * 10; + + private static void importUpdateVSP(VendorSoftwareProductObject vsp, boolean isUpdate, boolean restore) throws Exception { + String vspName = vsp.getName(); + boolean vspFound = HomePage.searchForVSP(vspName); + + if (vspFound) { + List<WebElement> elementsFromTable = GeneralPageElements.getElementsFromTable(); + elementsFromTable.get(0).click(); + elementsFromTable.get(0).click(); + GeneralUIUtils.waitForLoader(); + + if (isUpdate) { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.UPDATE_VSP.getValue()); + } else { + GeneralUIUtils.clickOnElementByTestId(DataTestIdEnum.ImportVfRepository.IMPORT_VSP.getValue()); + } + if (restore) { + GeneralPageElements.restoreComponentFromElementPage(vspName); + } + doCheckOut(); + //Metadata verification + onboardedVnfMetadataVerification(vsp, isUpdate); + String duration = GeneralUIUtils.getActionDuration(OnboardingUiUtils::waitUntilVnfCreated); + ExtentTestActions.log(Status.INFO, "Succeeded in importing/updating " + vspName, duration); + } else { + Assert.fail("Did not find VSP named " + vspName); + } + } + + private static void onboardedVnfMetadataVerification(VendorSoftwareProductObject vsp, boolean isUpdate) { + if (isUpdate) { + VfVerificator.verifyOnboardedVnfMetadataAfterUpdateVNF(vsp.getName(), vsp); + } else { + VfVerificator.verifyOnboardedVnfMetadata(vsp.getName(), vsp); + } + } + + public static boolean getVspValidationCongiguration() throws Exception { + return Boolean.parseBoolean(OnboardingUtils.getVspValidationConfiguration()); + } + + public static boolean putVspValidationCongiguration(boolean value) throws Exception { + return Boolean.parseBoolean(OnboardingUtils.putVspValidationConfiguration(value)); + } + + public static void doCheckOut() { + 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(); + } + } + + private static void waitUntilVnfCreated() { + ExtentTestActions.log(Status.INFO, "Clicking create/update VNF"); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.clickOnAreaJS(DataTestIdEnum.GeneralElementsEnum.CREATE_BUTTON.getValue()); + GeneralUIUtils.waitForLoader(WAITING_FOR_LOADER_TIME_OUT); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.GeneralElementsEnum.CHECKIN_BUTTON.getValue()); + } + + public static void updateVSP(VendorSoftwareProductObject vsp, boolean restore) throws Exception { + ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.getName()); + importUpdateVSP(vsp, true, restore); + } + + public static void updateVSP(VendorSoftwareProductObject vsp) throws Exception { + ExtentTestActions.log(Status.INFO, "Updating VSP " + vsp.getName()); + importUpdateVSP(vsp, true, false); + } + + public static void importVSP(VendorSoftwareProductObject vsp) throws Exception { + ExtentTestActions.log(Status.INFO, "Importing VSP " + vsp.getName()); + importUpdateVSP(vsp, false, false); + } + + public static void updateVnfAndValidate(String filePath, VendorSoftwareProductObject vsp, String updatedVnfFile, User user) throws Exception { + 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)); + + VendorSoftwareProductRestUtils.updateVendorSoftwareProductToNextVersion(vsp, user, filePath, updatedVnfFile); + HomePage.showVspRepository(); + updateVSP(vsp); + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + DeploymentArtifactPage.verifyArtifactsExistInTable(filePath, updatedVnfFile); + } + + public static VendorSoftwareProductObject createVSP(ResourceReqDetails resourceReqDetails, String vnfFile, String filepath, User user) throws Exception { + ExtentTestActions.log(Status.INFO, String.format("Creating VSP from package '%s'", vnfFile)); + final VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(user); + return VendorSoftwareProductRestUtils.createVSP(resourceReqDetails, vnfFile, filepath, user, vendorLicenseModel); + } + + + public static VendorSoftwareProductObject onboardAndValidate(ResourceReqDetails resourceReqDetails, 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)); + + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(user); + VendorSoftwareProductObject createVendorSoftwareProduct = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filepath, user, + vendorLicenseModel); + String vspName = createVendorSoftwareProduct.getName(); + + DownloadManager.downloadCsarByNameFromVSPRepository(vspName, createVendorSoftwareProduct.getVspId()); + File latestFilefromDir = FileHandling.getLastModifiedFileNameFromDir(); + + ExtentTestActions.log(Status.INFO, String.format("Going to import %s", vnfFile.substring(0, vnfFile.indexOf(".")))); + importVSP(createVendorSoftwareProduct); + + ResourceGeneralPage.getLeftMenu().moveToDeploymentArtifactScreen(); + + // Verify deployment artifacts + Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(latestFilefromDir.getAbsolutePath()); + + LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment")); + ArtifactsCorrelationManager.addVNFartifactDetails(vspName, deploymentArtifacts); + + List<String> 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<HeatMetaFirstLevelDefinition> deploymentArtifacts, + List<String> 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(); + } + + ArtifactUIUtils.validateArtifactNameVersionType(artifactName, artifactVersion, deploymentArtifact.getType()); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/PortMirroringUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/PortMirroringUtils.java new file mode 100644 index 0000000000..bfb81c160a --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/PortMirroringUtils.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ResourceCategoryEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.backend.ci.tests.utils.general.FileHandling; +import org.onap.sdc.backend.ci.tests.utils.rest.PropertyRestUtils; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.InputDefinition; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasElement; +import org.onap.sdc.frontend.ci.tests.datatypes.CanvasManager; +import org.onap.sdc.frontend.ci.tests.datatypes.ConnectionWizardPopUpObject; +import org.onap.sdc.frontend.ci.tests.datatypes.PortMirrioringConfigurationObject; +import org.onap.sdc.frontend.ci.tests.datatypes.PortMirroringEnum; +import org.onap.sdc.backend.ci.tests.datatypes.PropertyObject; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.ServiceContainer; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.datatypes.TopMenuButtonsEnum; +import org.onap.sdc.backend.ci.tests.datatypes.VendorLicenseModel; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.LifeCycleStatesEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.onap.sdc.backend.ci.tests.utils.general.OnboardingUtillViaApis; +import org.onap.sdc.backend.ci.tests.utils.general.VendorLicenseModelRestUtils; +import org.onap.sdc.backend.ci.tests.utils.general.VendorSoftwareProductRestUtils; + +import java.util.List; +import java.util.Map; + +public class PortMirroringUtils { + + + private static final int WAITING_FOR_LOADER_TIME_OUT = 2000; + + private PortMirroringUtils() { + + } + + public static ServiceContainer createServiceFromHeatFile(String filePath, String vnfFile) throws Throwable { +//1. Import VSP v1.0 + User sdncDesignerDetails1 = ElementFactory.getDefaultUser(UserRoleEnum.DESIGNER); + VendorLicenseModel vendorLicenseModel = VendorLicenseModelRestUtils.createVendorLicense(sdncDesignerDetails1); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software License (VLM): %s v1.0", vendorLicenseModel + .getVendorLicenseName())); + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResource(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Vendor Software Product (VSP): %s v1.0 from heat file: %s ", resourceReqDetails.getName(), vnfFile)); + VendorSoftwareProductObject vendorSoftwareProductObject = VendorSoftwareProductRestUtils.createVendorSoftwareProduct(resourceReqDetails, vnfFile, filePath, sdncDesignerDetails1, + vendorLicenseModel); +// VendorSoftwareProductObject vendorSoftwareProductObject = OnboardViaApis.fillVendorSoftwareProductObjectWithMetaData(vnfFile, createVendorSoftwareProduct); +//2. Create VF, certify - v1.0 is created + resourceReqDetails = OnboardingUtillViaApis.prepareOnboardedResourceDetailsBeforeCreate(resourceReqDetails, vendorSoftwareProductObject); + Resource resource = OnboardingUtillViaApis.createResourceFromVSP(resourceReqDetails); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Virtual Function (VF): %s v1.0", resourceReqDetails.getName())); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the VF")); +//3. Create Service add to it the certified VF and certify the Service v1.0 + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating Service: %s v1.0", serviceReqDetails.getName())); + Either<ComponentInstance, RestResponse> addComponentInstanceToComponentContainer = AtomicOperationUtils.addComponentInstanceToComponentContainer(resource, service, UserRoleEnum.DESIGNER, true); + ComponentInstance componentInstance = addComponentInstanceToComponentContainer.left().value(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding VF instance to Service")); + service = (Service) AtomicOperationUtils.changeComponentState(service, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Certify the Service")); + + return new ServiceContainer(service, resource, vendorSoftwareProductObject, vendorLicenseModel); + } + + public static Resource generatePNFAndUpdateInput(String resourceName, String vendorModelNumber, User user) throws Exception { + Resource resource = getresourcebytype(ResourceTypeEnum.PNF, resourceName, vendorModelNumber); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating pnf %s and certify it", resource.getName())); + Component componentObject = AtomicOperationUtils.getComponentObject(resource, UserRoleEnum.DESIGNER); + updateResourceInputViaAPI(user, componentObject, "physicalProbe", "nf_role"); + resource = (Resource) AtomicOperationUtils.changeComponentState(resource, UserRoleEnum.DESIGNER, LifeCycleStatesEnum.CERTIFY, true).getLeft(); + return resource; + } + + private static void updateResourceInputViaAPI(User user, Component componentObject, String defaultValue, String inputName) throws Exception { + List<InputDefinition> componentInputs = componentObject.getInputs(); + PropertyObject propertyObject = new PropertyObject(defaultValue, inputName, componentInputs.get(1).getParentUniqueId(), componentInputs.get(1).getUniqueId()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Update input %s to %s", "nf_role", "physicalProbe")); + PropertyRestUtils.updateInput(componentObject, propertyObject, user); + } + + public static Resource getresourcebytype(ResourceTypeEnum resourceTypeEnum, String resourceName, String vendorModelNumber) { + ResourceReqDetails resourceReqDetails = ElementFactory.getDefaultResourceByType(resourceTypeEnum, resourceName, ResourceCategoryEnum.NETWORK_L2_3_INFRASTRUCTURE, resourceName, vendorModelNumber); + return AtomicOperationUtils.createResourceByResourceDetails(resourceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + } + + public static String createproxyinstanceservicename(String serviceName, String instanceId) { + String serviceProxyInstanceName = String.format("%s_proxy %s", serviceName, instanceId); + return serviceProxyInstanceName; + } + + public static PortMirrioringConfigurationObject createPortMirriongConfigurationStructure(boolean isCapPropAssign) throws Throwable { + + //Using API onboard and certify 2 zip files Source: vmmme and Collector: Vprobe + String filePath = FileHandling.getPortMirroringRepositoryPath(); + ServiceContainer serviceContainerVmme_Source = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VMME_ZIP.getValue()); + ServiceContainer serviceContainerVprobe_Collector = PortMirroringUtils.createServiceFromHeatFile(filePath, PortMirroringEnum.VPROBE_ZIP.getValue()); + + // create service + ServiceReqDetails serviceReqDetails = ElementFactory.getDefaultService(); + //ServiceUIUtils.createService(serviceMetadata, getUser()); + + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating container %s: ", serviceReqDetails.getName())); + Service service = AtomicOperationUtils.createCustomService(serviceReqDetails, UserRoleEnum.DESIGNER, true).left().value(); + + String vmmeSourceName = serviceContainerVmme_Source.getService().getName(); + String vprobeSourceName = serviceContainerVprobe_Collector.getService().getName(); + + CatalogUIUtilitis.clickTopMenuButton(TopMenuButtonsEnum.CATALOG); + GeneralUIUtils.findComponentAndClick(service.getName()); + + ServiceGeneralPage.getLeftMenu().moveToCompositionScreen(); + CanvasManager canvasManager = CanvasManager.getCanvasManager(); + + CanvasElement serviceElementVmmeSourceName = canvasManager.createElementOnCanvas(vmmeSourceName); + + CanvasElement serviceElementVprobeCollector = canvasManager.createElementOnCanvas(vprobeSourceName); + + CompositionPage.searchForElement(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); + CanvasElement portMirroringConfigurationElement = canvasManager.createElementOnCanvas(PortMirroringEnum.PMC_ELEMENT_IN_PALLETE.getValue()); + + ConnectionWizardPopUpObject connectionWizardPopUpObjectVMME = new ConnectionWizardPopUpObject("", "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_SOURCE_CAP.getValue()); + ConnectionWizardPopUpObject connectionWizardPopUpObjectVProbe = new ConnectionWizardPopUpObject("", "", + PortMirroringEnum.PM_REQ_TYPE.getValue(), PortMirroringEnum.PMC_COLLECTOR_CAP.getValue()); + Map<String, String> capPropValues1 = null; + + if (isCapPropAssign) { + capPropValues1 = canvasManager.linkElementsWithCapPropAssignment(serviceElementVmmeSourceName, portMirroringConfigurationElement, connectionWizardPopUpObjectVMME); + GeneralUIUtils.waitForLoader(WAITING_FOR_LOADER_TIME_OUT); + canvasManager.linkElementsWithCapPropAssignment(serviceElementVprobeCollector, portMirroringConfigurationElement, connectionWizardPopUpObjectVProbe); + } else { + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVmmeSourceName, portMirroringConfigurationElement, connectionWizardPopUpObjectVMME); + canvasManager.linkElementsAndSelectCapReqTypeAndCapReqName(serviceElementVprobeCollector, portMirroringConfigurationElement, connectionWizardPopUpObjectVProbe); + } + + + PortMirrioringConfigurationObject portMirrioringConfigurationObject = new PortMirrioringConfigurationObject(serviceReqDetails, vmmeSourceName, + vprobeSourceName, canvasManager, serviceElementVmmeSourceName, serviceElementVprobeCollector, service, + portMirroringConfigurationElement, serviceContainerVmme_Source.getService(), serviceContainerVprobe_Collector.getService()); + + if (capPropValues1 != null) { + portMirrioringConfigurationObject.setCapPropValues(capPropValues1); + } + + return portMirrioringConfigurationObject; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ProductUIUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ProductUIUtils.java new file mode 100644 index 0000000000..f7fd4a63e0 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ProductUIUtils.java @@ -0,0 +1,90 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.ProductReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.ProductGeneralPage; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; + +import java.util.List; + +/** + * @author al714h + */ + +public class ProductUIUtils { + + protected static WebDriver driver; + + private ProductUIUtils() { + super(); + } + + private static void fillProductGeneralPage(ProductReqDetails product, User user) throws Exception { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Fill in metadata values in general page.. ")); + ProductGeneralPage.defineName(product.getName()); + ProductGeneralPage.defineFullName(product.getFullName()); + ProductGeneralPage.defineDescription(product.getDescription()); + ProductGeneralPage.defineProjectCode(product.getProjectCode()); + defineTagsList2(product.getTags()); + ProductGeneralPage.defineContactId(product.getContactId()); + GeneralUIUtils.clickSomewhereOnPage(); + } + + public static void createProduct(ProductReqDetails product, User user) throws Exception { + clikAddProduct(); + fillProductGeneralPage(product, user); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Product %s created", product.getName())); + } + + private static void defineTagsList2(List<String> productTags) { + WebElement productTagsTextbox = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.ProductMetadataEnum.TAGS.getValue()); + for (String tag : productTags) { + productTagsTextbox.clear(); + productTagsTextbox.sendKeys(tag); + GeneralUIUtils.waitForAngular(); + productTagsTextbox.sendKeys(Keys.ENTER); + } + } + + private static void clikAddProduct() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking Add Product button")); + try { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_PRODUCT.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exception on catched on Add Product button, retrying ...")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_PRODUCT.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/PropertiesUIUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/PropertiesUIUtils.java new file mode 100644 index 0000000000..9adc031c24 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/PropertiesUIUtils.java @@ -0,0 +1,97 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.onap.sdc.frontend.ci.tests.pages.PropertiesPage; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.WebElement; + +import java.util.HashMap; +import java.util.Map; + +public class PropertiesUIUtils { + + private static final int SLEEP_TIME = 2000; + + public static Map<String, String> addProperties(String name, String itemType, String defaultValue, + String description, String schemaType) throws Exception { + Map<String, String> propertyvalues = new HashMap<String, String>(); + GeneralUIUtils.getSelectList(itemType, "propertyType"); + ResourceUIUtils.definePropertyName(name); + if (itemType == "boolean") { + ResourceUIUtils.defineBoolenDefaultValue(defaultValue); + GeneralUIUtils.setWebElementByTestId("description", "description"); + Thread.sleep(SLEEP_TIME); + GeneralUIUtils.getWebElementByTestID("Add").click(); + } else if (itemType == "list" || itemType == "map") { + GeneralUIUtils.getSelectList(schemaType, "schemaType"); + } + if (!(itemType == "boolean")) { + ResourceUIUtils.defineDefaultValueByType(defaultValue); + GeneralUIUtils.setWebElementByTestId("description", "des"); + GeneralUIUtils.getWebElementByTestID("Add").click(); + Thread.sleep(SLEEP_TIME); + } + propertyvalues.put("type", itemType); + propertyvalues.put("defaultValue", defaultValue); + propertyvalues.put("description", description); + propertyvalues.put("name", name); + + return propertyvalues; + } + + public static void vlidateProperties(Map<String, String> propertyValues) throws InterruptedException { + WebElement name = GeneralUIUtils.getWebElementByTestID(propertyValues.get("name")); + name.getText().equalsIgnoreCase(propertyValues.get("name")); + WebElement defaultValue = GeneralUIUtils.getWebElementByTestID(propertyValues.get("name")); + defaultValue.getText().equalsIgnoreCase(propertyValues.get("defaultValue")); + WebElement type = GeneralUIUtils.getWebElementByTestID(propertyValues.get("type")); + type.getText().equalsIgnoreCase(propertyValues.get("type")); + } + + public static void addNewProperty(PropertyTypeEnum property) { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Adding new %s property", property.name())); + PropertiesPage.clickAddPropertyArtifact(); + PropertiesPage.getPropertyPopup().insertPropertyName(property.getName()); + PropertiesPage.getPropertyPopup().selectPropertyType(property.getType()); + PropertiesPage.getPropertyPopup().insertPropertyDescription(property.getDescription()); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(property.getValue()); + PropertiesPage.getPropertyPopup().clickSave(); + } + + public static void updateProperty(PropertyTypeEnum property) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating property: %s", property.name())); + PropertiesPage.clickOnProperty(property.getName()); + PropertiesPage.getPropertyPopup().insertPropertyDescription(property.getUpdateDescription()); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(property.getUpdateValue()); + PropertiesPage.getPropertyPopup().clickSave(); + } + + public static void changePropertyDefaultValueInComposition(String propertyName, String defaultValue) { + GeneralUIUtils.clickOnElementByTestId(propertyName); + PropertiesPage.getPropertyPopup().insertPropertyDefaultValue(defaultValue); + PropertiesPage.getPropertyPopup().clickSave(); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ResourceUIUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ResourceUIUtils.java new file mode 100644 index 0000000000..863b522e75 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ResourceUIUtils.java @@ -0,0 +1,396 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.CreateAndImportButtonsEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.Dashboard; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.StepsEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.openqa.selenium.By; +import org.openqa.selenium.ElementNotVisibleException; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; + +import java.io.File; +import java.util.List; +import java.util.Random; + +public final class ResourceUIUtils { + public static final String RESOURCE_NAME_PREFIX = "ResourceCDTest-"; + protected static final boolean IS_BEFORE_TEST = true; + public static final String INITIAL_VERSION = "0.1"; + public static final String ICON_RESOURCE_NAME = "call_controll"; + protected static final String UPDATED_RESOURCE_ICON_NAME = "objectStorage"; + private static final int BASIC_TIMEOUT = 10 * 60; + + private ResourceUIUtils() { + } + + private static WebDriver driver = GeneralUIUtils.getDriver(); + + // click and upload tosca file //**to be changed. + public static void importFileWithSendKey(String filePath, String fileName, CreateAndImportButtonsEnum type) + throws Exception { + WebElement importButton = HomeUtils.createAndImportButtons(type, driver).findElement(By.tagName("input")); + importButton.sendKeys(filePath + fileName); + } + + public static String defineUserId(String userId) { + // + WebElement resourceUserIdTextbox = ResourceGeneralPage.getContactIdField(); + resourceUserIdTextbox.clear(); + resourceUserIdTextbox.sendKeys(userId); + return userId; + } + + static String definePropertyName(String name) { + + WebElement nameProperty = GeneralUIUtils.getDriver().findElement(By.name("propertyName")); + nameProperty.sendKeys(name); + return name; + } + + public static void selectRandomResourceIcon() throws Exception { + final int webDriverWaitingTimeout = 4; + GeneralUIUtils.moveToStep(StepsEnum.ICON); + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), webDriverWaitingTimeout); + wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(@data-tests-id, 'iconBox')]"))); + List<WebElement> iconElement = GeneralUIUtils.getDriver() + .findElements(By.xpath("//*[contains(@data-tests-id, 'iconBox')]")); + iconElement.get(0).click(); + } + + static void defineDefaultValueByType(String value) { + + WebElement valueString = GeneralUIUtils.getDriver().findElement(By.name("value")); + valueString.clear(); + valueString.sendKeys(value); + } + + static void defineBoolenDefaultValue(String value) { + + WebElement elementBoolean = GeneralUIUtils.getDriver().findElement(By.name("value")); + Select se = new Select(elementBoolean); + se.selectByValue(value); + } + + public static void fillResourceGeneralInformationPage(ResourceReqDetails resource, User user, boolean isNewResource) { + try { + ResourceGeneralPage.defineName(resource.getName()); + ResourceGeneralPage.defineDescription(resource.getDescription()); + ResourceGeneralPage.defineCategory(resource.getCategories().get(0).getSubcategories().get(0).getName()); + ResourceGeneralPage.defineVendorName(resource.getVendorName()); + ResourceGeneralPage.defineVendorRelease(resource.getVendorRelease()); + if (isNewResource) { + ResourceGeneralPage.defineTagsList(resource, new String[]{"This-is-tag", "another-tag", "Test-automation-tag"}); + } else { + ResourceGeneralPage.defineTagsList(resource, new String[]{"one-more-tag"}); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static void fillMaxValueResourceGeneralInformationPage(ResourceReqDetails resource) { + final int stringPatternLength = 5000; + String stringPattern = "ABCDabcd123456"; + GeneralUIUtils.addStringtoClipboard(buildStringFromPattern(stringPattern, stringPatternLength)); + ResourceGeneralPage.defineNameWithPaste(); + ResourceGeneralPage.defineDescriptionWithPaste(); + ResourceGeneralPage.defineVendorNameWithPaste(); + ResourceGeneralPage.defineVendorReleaseWithPaste(); + ResourceGeneralPage.defineTagsListWithPaste(); + GeneralUIUtils.waitForAngular(); + } + + public static String buildStringFromPattern(String stringPattern, int stringLength) { + char[] chars = stringPattern.toCharArray(); + StringBuilder sb = new StringBuilder(); + Random random = new Random(); + for (int i = 0; i < stringLength; i++) { + char c = chars[random.nextInt(chars.length)]; + sb.append(c); + } + return sb.toString(); + } + + /** + * @deprecated Use {@link #createVF(ResourceReqDetails, User)} instead + */ + public static void createResource(ResourceReqDetails resource, User user) throws Exception { + createVF(resource, user); + } + + public static void createVF(ResourceReqDetails resource, User user) { + ExtentTestActions.log(Status.INFO, "Going to create a new VF."); + createResource(resource, user, DataTestIdEnum.Dashboard.BUTTON_ADD_VF); + } + + private static void createResource(ResourceReqDetails resource, User user, DataTestIdEnum.Dashboard button) { + WebElement addVFButton; + try { + GeneralUIUtils.ultimateWait(); + try { + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + addVFButton = GeneralUIUtils.getWebElementByTestID(button.getValue()); + } catch (Exception e) { + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resource.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "Add button is not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + showButtonsADD(); + addVFButton = GeneralUIUtils.getWebElementByTestID(button.getValue()); + } + addVFButton.click(); + GeneralUIUtils.ultimateWait(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on ADD button, retrying ... ")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.ultimateWait(); + GeneralUIUtils.getWebElementByTestID(button.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + fillResourceGeneralInformationPage(resource, user, true); + resource.setVersion("0.1"); + GeneralPageElements.clickCreateButton(); + } + + public static void updateResource(ResourceReqDetails resource, User user) { + ResourceGeneralPage.defineContactId(resource.getContactId()); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Updating General screen fields ...")); + fillResourceGeneralInformationPage(resource, user, false); + ResourceGeneralPage.clickUpdateButton(); + } + + /** + * Click on HTML element. + * + * @param dataTestId + * @throws Exception + */ + public static void getWebElementByTestID(String dataTestId) throws Exception { + final int webDriverWaitingTimeout = 20; + WebDriverWait wait = new WebDriverWait(GeneralUIUtils.getDriver(), webDriverWaitingTimeout); + WebElement element = wait + .until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-tests-id='" + dataTestId + "']"))); + element.click(); + // wait.until(ExpectedConditions.elemetto) + // WebElement serviceButton = + // GeneralUIUtils.getDriver().findElement(By.xpath("//*[@data-tests-id='" + // + dataTestId + "']")); + // serviceButton. + // serviceButton.click(); + } + + /** + * Import VFC + * + * @param user + * @param filePath + * @param fileName + * @return + * @throws Exception + */ + + public static void importVfc(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VFC resource ", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonVFC = GeneralUIUtils.findByText("Import VFC"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + if (!buttonVFC.isDisplayed()) { + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "VFC button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try { + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting VFC file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralPageElements.clickCreateButton(); + } + + public static void importVfcNoCreate(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + // Insert file to the browse dialog + WebElement buttonVFC = GeneralUIUtils.findByText("Import VFC"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VFC_FILE.getValue()); + if (!buttonVFC.isDisplayed()) { + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "VFC button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try { + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting VFC file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.waitForLoader(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + } + + + public static void importVfFromCsar(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VF asset resource %s", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonDCAE = GeneralUIUtils.findByText("Import DCAE asset"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + if (!buttonDCAE.isDisplayed()) { + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "DCAE button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try { + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting DCAE file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralPageElements.clickCreateButton(BASIC_TIMEOUT); + //GeneralUIUtils.ultimateWait(); "don't change import of csar can take longer then 3 minutes" + GeneralUIUtils.waitForLoader(BASIC_TIMEOUT); + } + + public static void importVfFromCsarNoCreate(ResourceReqDetails resourceMetaData, String filePath, String fileName, User user) + throws Exception { + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Creating new VF asset resource %s, Create button will not be clicked", resourceMetaData.getName())); + GeneralUIUtils.hoverOnAreaByTestId(Dashboard.IMPORT_AREA.getValue()); + GeneralUIUtils.ultimateWait(); + // Insert file to the browse dialog + WebElement buttonDCAE = GeneralUIUtils.findByText("Import DCAE asset"); + WebElement fileInputElement = GeneralUIUtils.getInputElement(DataTestIdEnum.Dashboard.IMPORT_VF_FILE.getValue()); + if (!buttonDCAE.isDisplayed()) { + File imageFilePath = GeneralUIUtils.takeScreenshot(null, SetupCDTest.getScreenshotFolder(), "Warning_" + resourceMetaData.getName()); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.WARNING, "DCAE button not visible after hover on import area of Home page, moving on ..." + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath)); + } + try { + fileInputElement.sendKeys(filePath + fileName); + } catch (ElementNotVisibleException e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exeption catched on file input, converting DCAE file input to visible")); + showButtons(); + fileInputElement.sendKeys(filePath + fileName); + } + // Fill the general page fields. + GeneralUIUtils.ultimateWait(); + fillResourceGeneralInformationPage(resourceMetaData, user, true); + GeneralUIUtils.waitForLoader(BASIC_TIMEOUT); + } + + public static void updateVfWithCsar(String filePath, String fileName) { + ExtentTestActions.log(Status.INFO, "Updating VF with updated CSAR file named " + fileName); + WebElement browseWebElement = GeneralUIUtils.getInputElement(DataTestIdEnum.GeneralElementsEnum.UPLOAD_FILE_INPUT.getValue()); + browseWebElement.sendKeys(filePath + fileName); + GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickUpdateButton(); + GeneralUIUtils.waitForLoader(); + ExtentTestActions.log(Status.INFO, "VF is updated."); + } + + private static void showButtons() { + String parentElementClassAttribute = "sdc-dashboard-import-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Input buttons now visible...")); + } + + private static void showButtonsADD() { + try { + GeneralUIUtils.ultimateWait(); + String parentElementClassAttribute = "sdc-dashboard-create-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + } catch (Exception e) { + GeneralUIUtils.ultimateWait(); + String parentElementClassAttribute = "sdc-dashboard-create-element-container"; + WebElement fileInputElementWithVisible = GeneralUIUtils.getDriver().findElement(By.className(parentElementClassAttribute)); + GeneralUIUtils.unhideElement(fileInputElementWithVisible, parentElementClassAttribute); + GeneralUIUtils.ultimateWait(); + } + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Input buttons now visible...")); + } + + public static void clickOnElementByText(String textToClick, String customizationFoLog) { + String customizationFoLogLocal = customizationFoLog != null ? customizationFoLog : ""; + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking on %s %s", textToClick, customizationFoLogLocal)); + GeneralUIUtils.clickOnElementByText(textToClick); + } + + public static void createPNF(ResourceReqDetails resource, User user) throws Exception { + ExtentTestActions.log(Status.INFO, "Going to create a new PNF"); + createResource(resource, user, DataTestIdEnum.Dashboard.BUTTON_ADD_PNF); + } + + public static void createCR(ResourceReqDetails resource, User user) throws Exception { + ExtentTestActions.log(Status.INFO, "Going to create a new CR"); + createResource(resource, user, DataTestIdEnum.Dashboard.BUTTON_ADD_CR); + } + + public static ImmutablePair<String, String> getFirstRIPos(ResourceReqDetails createResourceInUI, User user) { + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String xPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posX"); + String yPosPostDrag = (String) ((JSONObject) ((JSONArray) jsonResource.get("componentInstances")).get(0)) + .get("posY"); + return new ImmutablePair<String, String>(xPosPostDrag, yPosPostDrag); + + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/RestCDUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/RestCDUtils.java new file mode 100644 index 0000000000..b090fac4be --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/RestCDUtils.java @@ -0,0 +1,214 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.http.HttpStatus; +import org.codehaus.jettison.json.JSONObject; +import org.onap.sdc.backend.ci.tests.config.Config; +import org.onap.sdc.backend.ci.tests.datatypes.ComponentReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.utils.general.ElementFactory; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.DriverFactory; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.backend.ci.tests.utils.rest.CatalogRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.CategoryRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ResourceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser; +import org.onap.sdc.backend.ci.tests.utils.rest.ServiceRestUtils; +import org.onap.sdc.backend.ci.tests.utils.rest.UserRestUtils; + +public class RestCDUtils { + + private static final int SLEEP_DURATION = 1000; + + private static void setResourceUniqueIdAndUUID(ComponentReqDetails element, RestResponse getResourceResponse) { + element.setUniqueId(ResponseParser.getUniqueIdFromResponse(getResourceResponse)); + element.setUUID(ResponseParser.getUuidFromResponse(getResourceResponse)); + } + + public static RestResponse getResource(ResourceReqDetails resource, User user) { + final String getResourceMsg = "Trying to get resource named " + resource.getName() + " with version " + resource.getVersion(); + final String succeedGetResourceMsg = "Succeeded to get resource named " + resource.getName() + " with version " + resource.getVersion(); + final String failedGetResourceMsg = "Failed to get resource named " + resource.getName() + " with version " + resource.getVersion(); + try { + ExtentTestActions.log(Status.INFO, getResourceMsg); + System.out.println(getResourceMsg); + GeneralUIUtils.sleep(SLEEP_DURATION); + RestResponse getResourceResponse = null; + String resourceUniqueId = resource.getUniqueId(); + if (resourceUniqueId != null) { + getResourceResponse = ResourceRestUtils.getResource(resourceUniqueId); + if (getResourceResponse.getErrorCode().intValue() == HttpStatus.SC_OK) { + ExtentTestActions.log(Status.INFO, succeedGetResourceMsg); + System.out.println(succeedGetResourceMsg); + } + return getResourceResponse; + } + JSONObject getResourceJSONObject = null; + getResourceResponse = ResourceRestUtils.getResourceByNameAndVersion(user.getUserId(), resource.getName(), resource.getVersion()); + if (getResourceResponse.getErrorCode().intValue() == HttpStatus.SC_OK) { + setResourceUniqueIdAndUUID(resource, getResourceResponse); + ExtentTestActions.log(Status.INFO, succeedGetResourceMsg); + System.out.println(succeedGetResourceMsg); + return getResourceResponse; + } + ExtentTestActions.log(Status.INFO, failedGetResourceMsg); + return getResourceResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static RestResponse getService(ServiceReqDetails service, User user) { + final int threadSleepTime = 3500; + try { + Thread.sleep(threadSleepTime); + RestResponse getServiceResponse = ServiceRestUtils.getServiceByNameAndVersion(user, service.getName(), + service.getVersion()); + if (getServiceResponse.getErrorCode().intValue() == HttpStatus.SC_OK) { + setResourceUniqueIdAndUUID(service, getServiceResponse); + } + return getServiceResponse; + } catch (Exception e) { + throw new RuntimeException(e); + } + + } + + public static String getExecutionHostAddress() { + + String computerName = null; + try { + computerName = InetAddress.getLocalHost().getHostAddress().replaceAll("\\.", "·"); + System.out.println(computerName); + if (computerName.contains(".")) { + computerName = computerName.substring(0, computerName.indexOf(".")).toUpperCase(); + } + } catch (UnknownHostException e) { + System.out.println("Uknown hostAddress"); + } + return computerName != null ? computerName : "Uknown hostAddress"; + } + + public static Map<String, List<Component>> getCatalogAsMap() throws IOException { + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + RestResponse catalog = CatalogRestUtils.getCatalog(defaultAdminUser.getUserId()); + return ResponseParser.convertCatalogResponseToJavaObject(catalog.getResponse()); + } + + public static Map<String, List<CategoryDefinition>> getCategories() throws Exception { + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + + Map<String, List<CategoryDefinition>> map = new HashMap<>(); + + + RestResponse allResourceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.RESOURCE_PARAM_NAME); + RestResponse allServiceCategories = CategoryRestUtils.getAllCategories(defaultAdminUser, ComponentTypeEnum.SERVICE_PARAM_NAME); + + List<CategoryDefinition> parsedResourceCategories = ResponseParser.parseCategories(allResourceCategories); + List<CategoryDefinition> parsedServiceCategories = ResponseParser.parseCategories(allServiceCategories); + + map.put(ComponentTypeEnum.RESOURCE_PARAM_NAME, parsedResourceCategories); + map.put(ComponentTypeEnum.SERVICE_PARAM_NAME, parsedServiceCategories); + + return map; + } + + + public static void deleteCreatedComponents(Map<String, List<Component>> map) throws IOException { + + System.out.println("going to delete all created components..."); + + User defaultAdminUser = ElementFactory.getDefaultUser(UserRoleEnum.ADMIN); + final String userId = defaultAdminUser.getUserId(); + + + List<Component> resourcesArrayList = map.get("resources"); + List<String> collect = resourcesArrayList.stream().filter(s -> s.getName().startsWith(ElementFactory.getResourcePrefix())). + map(e -> e.getUniqueId()). + collect(Collectors.toList()); + for (String uId : collect) { + ResourceRestUtils.markResourceToDelete(uId, userId); + + } + ResourceRestUtils.deleteMarkedResources(userId); + + resourcesArrayList = map.get("services"); + collect = resourcesArrayList.stream(). + filter(e -> e != null). + filter(e -> e.getName() != null). + filter(s -> s.getName().startsWith(ElementFactory.getServicePrefix())). + filter(e -> e.getUniqueId() != null). + map(e -> e.getUniqueId()). + collect(Collectors.toList()); + for (String uId : collect) { + ServiceRestUtils.markServiceToDelete(uId, userId); + } + ServiceRestUtils.deleteMarkedServices(userId); + + } + + public static String getUserRole(User reqUser, User user) { + try { + RestResponse getUserRoleResp = UserRestUtils.getUserRole(reqUser, user); + JSONObject jObject = new JSONObject(getUserRoleResp.getResponse()); + return jObject.getString("role"); + } catch (Exception e) { + return null; + } + } + + public static RestResponse getUser(User reqUser, User user) { + try { + return UserRestUtils.getUser(reqUser, user); + } catch (Exception e) { + return null; + } + } + + /*************************************/ + + public static void deleteOnDemand() throws IOException { + Config config = DriverFactory.getConfig(); + if (!config.getSystemUnderDebug()) { + deleteCreatedComponents(getCatalogAsMap()); + } else { + System.out.println("According to configuration components will not be deleted, in case to unable option to delete, please change systemUnderDebug parameter value to false ..."); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ServiceUIUtils.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ServiceUIUtils.java new file mode 100644 index 0000000000..48fb0b8efb --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/utilities/ServiceUIUtils.java @@ -0,0 +1,110 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.utilities; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ServiceCategoriesEnum; +import org.onap.sdc.frontend.ci.tests.pages.GeneralPageElements; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.openqa.selenium.Keys; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.interactions.Actions; + +import java.util.ArrayList; +import java.util.List; + +public class ServiceUIUtils { + + private ServiceUIUtils() { + + } + + private static void defineTagsList2(List<String> serviceTags) { + WebElement serviceTagsTextbox = GeneralUIUtils.getWebElementByTestID("i-sdc-tag-input"); + for (String tag : serviceTags) { + serviceTagsTextbox.clear(); + serviceTagsTextbox.sendKeys(tag); + GeneralUIUtils.waitForAngular(); + serviceTagsTextbox.sendKeys(Keys.ENTER); + } + } + + public static void fillServiceGeneralPage(final ServiceReqDetails service) { + SetupCDTest.getExtendTest().log(Status.INFO, "Fill in metadata values in general page"); + ServiceGeneralPage.defineName(service.getName()); + ServiceGeneralPage.defineDescription(service.getDescription()); + ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName()); + ServiceGeneralPage.defineServiceFunction(service.getServiceFunction()); + ServiceGeneralPage.defineNamingPolicy(service.getNamingPolicy()); + defineTagsList2(service.getTags()); + ServiceGeneralPage.defineContactId(service.getContactId()); + GeneralUIUtils.clickSomewhereOnPage(); + } + + public static void createService(ServiceReqDetails service) { + clickAddService(); + fillServiceGeneralPage(service); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("The service %s was created", service.getName())); + } + + public static void setServiceCategory(ServiceReqDetails service, ServiceCategoriesEnum category) { + CategoryDefinition categoryDefinition = new CategoryDefinition(); + categoryDefinition.setName(category.getValue()); + List<CategoryDefinition> categories = new ArrayList<>(); + categories.add(categoryDefinition); + service.setCategories(categories); + } + + public static void createServiceWithDefaultTagAndUserId(ServiceReqDetails service, User user) { + clickAddService(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Defining General Page fields")); + ServiceGeneralPage.defineName(service.getName()); + ServiceGeneralPage.defineDescription(service.getDescription()); + ServiceGeneralPage.defineCategory(service.getCategories().get(0).getName()); + ServiceGeneralPage.defineProjectCode(service.getProjectCode()); + ServiceGeneralPage.defineInstantiationType(service.getInstantiationType()); + GeneralUIUtils.ultimateWait(); + GeneralPageElements.clickCreateButton(); + SetupCDTest.getExtendTest().log(Status.INFO, "Done creating service over the UI, " + + "about to move into Tosca Artifacts section."); + } + + public static void clickAddService() { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Clicking the Add Service button")); + try { + GeneralUIUtils.hoverOnAreaByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue()); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + //GeneralUIUtils.hoverAndClickOnButtonByTestId(DataTestIdEnum.Dashboard.ADD_AREA.getValue(),DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()); + GeneralUIUtils.ultimateWait(); + } catch (Exception e) { + SetupCDTest.getExtendTest().log(Status.WARNING, String.format("Exception on catched on Add Service button, retrying ...")); + GeneralUIUtils.hoverOnAreaByClassName("w-sdc-dashboard-card-new"); + GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.Dashboard.BUTTON_ADD_SERVICE.getValue()).click(); + GeneralUIUtils.ultimateWait(); + } + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/CatalogVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/CatalogVerificator.java new file mode 100644 index 0000000000..bf3db5df03 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/CatalogVerificator.java @@ -0,0 +1,168 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum; +import org.openecomp.sdc.be.model.Component; +import org.openecomp.sdc.be.model.DistributionStatusEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.TypesEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.testng.Assert; +import org.testng.TestNGException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class CatalogVerificator { + + private CatalogVerificator() { + + } + + public static int getResourceNumber(ResourceTypeEnum resourceType, Map<String, List<Component>> catalogAsMap) throws Exception { + List<Component> resourcesArrayList = catalogAsMap.get("resources"); + return resourcesArrayList.stream(). + filter(s -> ((Resource) s).getResourceType().equals(resourceType)). + collect(Collectors.toList()).size(); + } + + public static int getTypeNumber(TypesEnum enumtype) throws Exception { + Map<String, List<Component>> catalogAsMap = RestCDUtils.getCatalogAsMap(); + switch (enumtype) { + case RESOURCE: + return catalogAsMap.get("resources").size(); + case SERVICE: + return catalogAsMap.get("services").size(); + case PRODUCT: + return catalogAsMap.get("products").size(); + default: + return getResourceNumber(ResourceTypeEnum.valueOf(enumtype.name()), catalogAsMap); + } + } + + public static void validateType(TypesEnum enumtype) throws Exception { + int numberOfElementsFromBE = getTypeNumber(enumtype); + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s elements, should be %s ...", enumtype.name(), numberOfElementsFromBE)); + Assert.assertEquals(numberOfElementsFromBE, numberOfElementsFromUI, String.format("Expected : %s, Actual: %s", numberOfElementsFromBE, numberOfElementsFromUI)); + } + + public static int getStatusNumber(List<LifeCycleStateEnum> status) throws Exception { + Map<String, List<Component>> catalogAsMap = RestCDUtils.getCatalogAsMap(); + return catalogAsMap.entrySet().stream(). + map(s -> s.getValue()). + flatMap(List::stream). + filter(s -> (s != null && status.contains(mapBeLifecycleToUIStatus(s)))). + collect(Collectors.toList()).size(); + } + + public static void validateStatus(List<LifeCycleStateEnum> status, String checkboxName) throws Exception { + int numberOfElementsFromBE = getStatusNumber(status); + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s elements , should be %s ...", checkboxName, numberOfElementsFromBE)); + Assert.assertEquals(numberOfElementsFromBE, numberOfElementsFromUI, String.format("Expected : %s, Actual: %s", numberOfElementsFromBE, numberOfElementsFromUI)); + } + + public static int getCategoryNumber(String categoryName) throws Exception { + Map<String, List<Component>> catalogAsMap = RestCDUtils.getCatalogAsMap(); + List<Component> serviceAndResourceList = new ArrayList<>(); + serviceAndResourceList.addAll(catalogAsMap.get("resources")); + serviceAndResourceList.addAll(catalogAsMap.get("services")); + List<Component> list = new ArrayList<>(); + if (!serviceAndResourceList.isEmpty()) { + for (Component s : serviceAndResourceList) { + if (s.getCategories().get(0).getName().equals(categoryName)) { + list.add(s); + } + } + } + return list.size(); + } + + public static void validateCategory(String categoryName) throws Exception { + //int numberOfElementsFromBE = getCategoryNumber(categoryName); + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s category elements , should be %s ...", categoryName, "more or equal to 0 elements ")); + Assert.assertTrue(numberOfElementsFromUI >= 0, String.format("Expected : %s, Actual: %s", "more or equal to 0 elements ", numberOfElementsFromUI)); + } + + public static int getSubCategoryNumber(String categoryName, String subCategoryName) throws Exception { + Map<String, List<Component>> catalogAsMap = RestCDUtils.getCatalogAsMap(); + List<Component> resourcesArrayList = catalogAsMap.get("resources"); + List<Component> list = new ArrayList<>(); + if (!resourcesArrayList.isEmpty()) { + for (Component s : resourcesArrayList) { + if (s.getCategories().get(0).getName().equalsIgnoreCase(categoryName) + && s.getCategories().get(0).getSubcategories().get(0).getName().equalsIgnoreCase(subCategoryName)) { + list.add(s); + } + } + } + return list.size(); + } + + public static void validateSubCategory(String categoryName, String subCategoryName) throws Exception { + //int numberOfElementsFromBE = getSubCategoryNumber(categoryName, subCategoryName); + + int numberOfElementsFromUI = getNumberOfElementsFromCatalogHeader(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating number of %s/%s subcategory elements , should be %s ...", categoryName, subCategoryName, "more then 0 elements ")); + Assert.assertTrue(numberOfElementsFromUI > 0, String.format("Expected : %s, Actual: %s", "more then 0 elements ", numberOfElementsFromUI)); + } + + public static int getNumberOfElementsFromCatalogHeader() { + String elementsAsString = GeneralUIUtils.getWebElementByClassName("w-sdc-dashboard-catalog-items-header").getText(); + String numberOfElementsAsString = elementsAsString.split(" ")[0]; + if (numberOfElementsAsString.equals("No")) { + return 0; + } else { + return Integer.parseInt(numberOfElementsAsString); + } + } + + private static LifeCycleStateEnum mapBeLifecycleToUIStatus(Component component) { + boolean isServiceAndDistributed = component.getComponentType().equals(ComponentTypeEnum.SERVICE) + && ((Service) component).getDistributionStatus().equals(DistributionStatusEnum.DISTRIBUTED); + switch (component.getLifecycleState()) { + case CERTIFIED: + if (isServiceAndDistributed) { + return LifeCycleStateEnum.DISTRIBUTED; + } else { + return LifeCycleStateEnum.CERTIFIED; + } + case NOT_CERTIFIED_CHECKIN: + return LifeCycleStateEnum.CHECKIN; //to IN DESIGN + case NOT_CERTIFIED_CHECKOUT: + return LifeCycleStateEnum.CHECKOUT; //to IN DESIGN + default: + throw new TestNGException("Missing enum value in enum converter"); + } + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/CustomizationUUIDVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/CustomizationUUIDVerificator.java new file mode 100644 index 0000000000..f52d1e92f9 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/CustomizationUUIDVerificator.java @@ -0,0 +1,48 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.testng.AssertJUnit.assertTrue; + +public class CustomizationUUIDVerificator { + + public static void validateCustomizationUUIDuniqueness(List customizationUUIDs) { + boolean hasNoDuplicates = CustomizationUUIDVerificator.containsUnique(customizationUUIDs); + assertTrue("There are duplicate customizationUUIDs in list", hasNoDuplicates); + } + + private static <T> boolean containsUnique(List<T> list) { + Set<T> set = new HashSet<>(); + + for (T t : list) { + if (!set.add(t)) { + return false; + } + } + + return true; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/DeploymentViewVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/DeploymentViewVerificator.java new file mode 100644 index 0000000000..386ec92b0f --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/DeploymentViewVerificator.java @@ -0,0 +1,346 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.apache.commons.io.FileUtils; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.execute.devCI.ArtifactFromCsar; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentPage; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.backend.ci.tests.utils.ToscaParserUtils; +import org.openqa.selenium.WebElement; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +public class DeploymentViewVerificator { + + //GroupPropertyEnum.getGroupPropertyNames(); + private static List<String> currentPropertiesForUI = Arrays.asList("isBase", + "vf_module_label", + "vf_module_description", + "min_vf_module_instances", + "max_vf_module_instances", + "initial_count", + "vf_module_type", //works as isBase property, value can be Base/Expantion + "volume_group", + "vfc_list", + "availability_zone_count"); + + //GroupPropertyEnum.getGroupPropertyNamesWithoutIsbase(); + private static List<String> currentPropertiesWithoutIsBaseForFile = Arrays.asList("vf_module_label", + "vf_module_description", + "min_vf_module_instances", + "max_vf_module_instances", + "initial_count", + "vf_module_type", //works as isBase property, value can be Base/Expantion + "volume_group", + "vfc_list", + "availability_zone_count"); + + public static List<String> getCurrentProperties() { + return currentPropertiesForUI; + } + + static List<String> getCurrentPropertiesWithoutIsBase() { + return currentPropertiesWithoutIsBaseForFile; + } + + + private static final String PART_TO_REPLACE = "_group"; + + private static Map<String, HashMap<String, List<String>>> deploymentViewData = new HashMap<String, HashMap<String, List<String>>>() { + { + HashMap<String, List<String>> segw_heat_c3_base, segw_heat_c3_VMs1; + + segw_heat_c3_base = new HashMap<String, List<String>>(); + segw_heat_c3_base.put("members", Arrays.asList("segw_internet_security_group", "segw_security_group", "int_layer2vlan_net")); + segw_heat_c3_base.put("artifacts", Arrays.asList("segw_heat_c3_base.yml", "segw_heat_c3_base.env")); + segw_heat_c3_base.put("properties", currentPropertiesForUI); + put("segw_heat_c3_base", segw_heat_c3_base); + segw_heat_c3_VMs1 = new HashMap<String, List<String>>(); + segw_heat_c3_VMs1.put("members", Arrays.asList("segw_oam_protected_0_port", + "fw_oam_int_layer2vlan_1_port", + "segw_0", "segw_internet_1_port", + "segw_layer2vlan_2_port", + "fw_gn_0", "fw_gn_hsl_direct_3_port", + "fw_oam_oam_mgmt_0_port", + "fw_oam_hsl_direct_3_port", + "fw_gn_oam_mgmt_0_port", + "fw_oam_oam_direct_2_port", + "fw_gn_gn_direct_2_port", + "fw_oam_0", + "fw_gn_int_layer2vlan_1_port")); + segw_heat_c3_VMs1.put("artifacts", Arrays.asList("segw_heat_c3_VMs1.yml", "segw_heat_c3_VMs1.env")); + segw_heat_c3_VMs1.put("properties", currentPropertiesForUI); + put("segw_heat_c3_VMs1", segw_heat_c3_VMs1); + } + }; + + private static Map<String, HashMap<String, List<String>>> deploymentViewDataMixedArtifacts = new HashMap<String, HashMap<String, List<String>>>() { + { + HashMap<String, List<String>> module_1_ldsa, module_2_ldsa, base_ldsa; + + module_1_ldsa = new HashMap<String, List<String>>(); + module_1_ldsa.put("members", Stream.of("ltm_oam_protected_0_port", "ltm_dmz_direct_0_port", "ltm_server_0").collect(Collectors.toList())); + module_1_ldsa.put("artifacts", Stream.of("module_1_ldsa.yaml", "module_1_ldsa.env", "base_ldsa.33.yaml", "module_1_ldsa.11.yaml").collect(Collectors.toList())); + module_1_ldsa.put("properties", currentPropertiesForUI); + put("module_1_ldsa", module_1_ldsa); + module_2_ldsa = new HashMap<String, List<String>>(); + module_2_ldsa.put("members", Stream.of("ltm_server_0").collect(Collectors.toList())); + module_2_ldsa.put("artifacts", Stream.of("module_2_ldsa.yaml", "module_2_ldsa.env", "base_ldsa.3.yaml", "module_2_ldsa.22.yaml").collect(Collectors.toList())); + module_2_ldsa.put("properties", currentPropertiesForUI); + put("module_2_ldsa", module_2_ldsa); + base_ldsa = new HashMap<String, List<String>>(); + base_ldsa.put("members", Stream.of("ldsa_sec_grp_1").collect(Collectors.toList())); + base_ldsa.put("artifacts", Stream.of("base_ldsa.yaml", "module_2_ldsa.2.yaml", "module_1_ldsa.1.yaml").collect(Collectors.toList())); + base_ldsa.put("properties", currentPropertiesForUI); + put("base_ldsa", base_ldsa); + } + }; + + + private Map<String, HashMap<String, List<String>>> deploymentViewDataFromFile; + + public DeploymentViewVerificator(String pathToCsar) throws Exception { + deploymentViewDataFromFile = buildDeploymentViewDataFromCSAR(pathToCsar); + } + + public DeploymentViewVerificator() throws Exception { + deploymentViewDataFromFile = deploymentViewDataMixedArtifacts; + } + + + public void verifyDeploymentPageSubElements(String moduleName) throws Exception { + HashMap<String, List<String>> moduleProperties = getDeploymentViewData().get(moduleName); + + // add env placeholder to deployment view data + if (!moduleProperties.get("artifacts").contains(moduleName + ".env")) { + moduleProperties.get("artifacts").add(moduleName + ".env"); + } + + List<WebElement> members, artifacts, properties; + members = DeploymentPage.getGroupMembersList(moduleName); + artifacts = DeploymentPage.getArtifactNames(); + properties = DeploymentPage.getPropertyNames(); + + File imageFilePath = GeneralUIUtils.takeScreenshot(moduleName + UUID.randomUUID(), SetupCDTest.getScreenshotFolder(), null); + final String absolutePath = new File(SetupCDTest.getReportFolder()).toURI().relativize(imageFilePath.toURI()).getPath(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating group %s, should be %s members, %s artifacts " + SetupCDTest.getExtendTest().addScreenCaptureFromPath(absolutePath), + moduleName, moduleProperties.get("members").size(), moduleProperties.get("artifacts").size())); + + assertTrue(moduleProperties.get("artifacts").size() == artifacts.size(), "Artifacts amount not as expected, expected " + moduleProperties.get("artifacts").size()); + assertTrue(moduleProperties.get("artifacts").containsAll(artifacts.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + assertTrue(moduleProperties.get("members").size() == members.size(), "Members amount not as expected, expected " + moduleProperties.get("members").size()); + assertTrue(moduleProperties.get("members").containsAll(members.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + assertTrue(moduleProperties.get("properties").size() == properties.size(), "Properties amount not as expected, expected " + moduleProperties.get("properties").size()); + assertTrue(moduleProperties.get("properties").containsAll(properties.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + DeploymentPage.clickOnProperties(); + DeploymentPage.clickOnArtifacts(); + } + + public void verifyDeploymentPageModules(List<WebElement> modules) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating VF groups , should be %s groups ", getDeploymentViewData().size())); + assertFalse(modules.isEmpty(), "No modules found"); + assertTrue(modules.size() == getDeploymentViewData().size(), "Modules amount not as expected, expected " + getDeploymentViewData().size()); + for (WebElement module : modules) { + assertTrue(getDeploymentViewData().containsKey(module.getText().split("\\.\\.")[1])); + } + } + + public static void verifyComponentNameChanged(String oldName, String newName) { + final int clickingElementTimeout = 10; + try { + GeneralUIUtils.clickOnElementByText(oldName, clickingElementTimeout); + assertTrue(false, "Element name don't changed"); + } catch (Exception e) { + GeneralUIUtils.clickOnElementByText(newName); + } + } + + public Map<String, HashMap<String, List<String>>> getDeploymentViewData() { + return getDeploymentViewDataFromFile(); + } + + public static Map<String, HashMap<String, List<String>>> buildDeploymentViewDataFromCSAR(String pathToCSAR) throws Exception { + ToscaDefinition toscaDefinition = ToscaParserUtils.parseToscaMainYamlToJavaObjectByCsarLocation(new File(pathToCSAR)); + Map<String, HashMap<String, List<String>>> deploymentViewDataFromFile = new HashMap<String, HashMap<String, List<String>>>(); + Map<String, ToscaGroupsTopologyTemplateDefinition> groups = toscaDefinition.getTopology_template().getGroups(); + List<String> keyList = groups.keySet().stream().collect(Collectors.toList()); + HashMap<String, List<String>> groupsToArtifacts = getDeploymentArtifactsMappedToGroupsFromCSAR(pathToCSAR); + for (String groupKey : keyList) { + HashMap<String, List<String>> tempGroupMap = new HashMap<String, List<String>>(); + tempGroupMap.put("artifacts", groupsToArtifacts.get(convertAmdocsCsarGroupNameToSdcCsarGroupName(groupKey))); + if (groups.get(groupKey).getMembers() == null) { + tempGroupMap.put("members", Arrays.asList()); + } else { + tempGroupMap.put("members", groups.get(groupKey).getMembers()); + } + tempGroupMap.put("properties", currentPropertiesForUI); + deploymentViewDataFromFile.put(convertAmdocsCsarGroupNameToSdcCsarGroupName(groupKey), tempGroupMap); + } + return deploymentViewDataFromFile; + } + + public static HashMap<String, List<String>> getDeploymentArtifactsMappedToGroupsFromCSAR(String pathToFile) throws Exception { + Map<String, Object> combinedMap = ArtifactFromCsar.combineHeatArtifacstWithFolderArtifacsToMap(pathToFile); + LinkedList<HeatMetaFirstLevelDefinition> deploymentArtifacts = ((LinkedList<HeatMetaFirstLevelDefinition>) combinedMap.get("Deployment")); + + HashMap<String, List<String>> tempGroupMap = new HashMap<String, List<String>>(); + for (HeatMetaFirstLevelDefinition deploymentArtifact : deploymentArtifacts) { + String groupName = deploymentArtifact.getFileName().trim().substring(0, deploymentArtifact.getFileName().indexOf(".")); + if (deploymentArtifact.getType().equals("HEAT") || deploymentArtifact.getType().equals("HEAT_NET") || deploymentArtifact.getType().equals("HEAT_VOL")) { + List<String> list = new ArrayList<>(); + list.add(deploymentArtifact.getFileName().trim()); + tempGroupMap.put(groupName, list); + } else { + // update current key + List<String> list = tempGroupMap.get(groupName); + list.add(deploymentArtifact.getFileName().trim()); + tempGroupMap.put(groupName, list); + } + } + return tempGroupMap; + } + + + public static void cleanFolders(String outputFolder) throws IOException { + System.gc(); + FileUtils.cleanDirectory(new File(outputFolder)); + FileUtils.deleteDirectory(new File(outputFolder)); + } + + public static String unzipCsarFile(String pathToCsar) { + File csarFile = new File(pathToCsar); + + + File dir = new File(csarFile.getParent() + File.separator + "output" + UUID.randomUUID() + File.separator + UUID.randomUUID()); + if (!dir.exists()) { + dir.mkdirs(); + } + + String outputFolder = dir.getPath(); + ArtifactFromCsar.unZip(pathToCsar, outputFolder); + return outputFolder; + } + + public static void validateEditPopoverFields(String expectedVNFName, String expectedHeatName, String expectedModuleName) { + String VNFname = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.RESOURCE_NAME_ON_POPOVER.getValue()).getText(); + String heatName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.NAME_INPUT.getValue()).getAttribute("value"); + String moduleName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.DeploymentScreen.MODULE_NAME_ON_POPOVER.getValue()).getText(); + assertTrue(expectedVNFName.equals(VNFname), String.format("VNF name Expected: %s, Actual: %s ", expectedVNFName, VNFname)); + assertTrue(expectedHeatName.equals(heatName), String.format("HEAT name Expected: %s, Actual: %s ", expectedHeatName, heatName)); + assertTrue(expectedModuleName.equals(moduleName), String.format("Module name Expected: %s, Actual: %s ", expectedModuleName, moduleName)); + } + + public static void validateEditPopoverButtons(String newName, String invalidModuleName, String validModueName) { + DeploymentPage.updateAndCancel(newName, DataTestIdEnum.DeploymentScreen.X_BUTTON); + verifyComponentNameChanged(invalidModuleName, validModueName); + DeploymentPage.clickOnEditIcon(); + DeploymentPage.updateAndCancel(newName, DataTestIdEnum.DeploymentScreen.CANCEL); + verifyComponentNameChanged(invalidModuleName, validModueName); + } + + public static void validateEditPopover() throws Exception { + String moduleRowText = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()).get(0).getText(); + DeploymentPage.clickOnModuleName(moduleRowText); + DeploymentPage.clickOnEditIcon(); + String[] splitedModuleName = moduleRowText.split("\\.\\."); + + validateEditPopoverFields(splitedModuleName[0], splitedModuleName[1], splitedModuleName[2]); + + String newName = "kuku"; + String newModuleName = DeploymentPage.reconstructModuleName(splitedModuleName, newName); + validateEditPopoverButtons(newName, newModuleName, moduleRowText); + } + + private Map<String, HashMap<String, List<String>>> getDeploymentViewDataFromFile() { + return deploymentViewDataFromFile; + } + + public static void validateModuleNameUpadate() throws Exception { + List<WebElement> moduleRowsFromTable = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()); + int i = 0; + for (WebElement moduleRow : moduleRowsFromTable) { + String moduleRowText = moduleRow.getText(); + String updatedName = "updatedName" + i; + DeploymentPage.updateModuleName(moduleRowText, updatedName); + String updatedModuleName = DeploymentPage.reconstructModuleName(moduleRowText.split("\\.\\."), updatedName); + verifyComponentNameChanged(moduleRowText, updatedModuleName); + // Close module + GeneralUIUtils.clickOnElementByText(updatedModuleName); + i++; + } + } + + public static void regularDepoymentScreenVerificator(Map<String, HashMap<String, String>> metaDataFromUI, DeploymentViewVerificator verificator) throws Exception, InterruptedException { + ResourceGeneralPage.getLeftMenu().moveToDeploymentViewScreen(); + List<WebElement> moduleRowsFromTable = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DeploymentScreen.MODULES.getValue()); + verificator.verifyDeploymentPageModules(moduleRowsFromTable); + for (WebElement moduleRow : moduleRowsFromTable) { + String moduleRowText = moduleRow.getText(); + String middleName = moduleRowText.split("\\.\\.")[1]; + verificator.verifyDeploymentPageSubElements(middleName); + if (metaDataFromUI != null) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating %s group version, should be %s ", moduleRowText, metaDataFromUI.get(moduleRowText.split("\\.\\.")[1]))); + String groupVersion = DeploymentPage.getGroupVersion().split(":")[1].trim(); + String increasedVersion = String.valueOf(Integer.parseInt(metaDataFromUI.get(middleName).get("version")) + 1); + assertTrue(groupVersion.equals(increasedVersion)); + if (metaDataFromUI.get(middleName).get("moduleID") != "primary") { + String moduleID = DeploymentPage.getModuleID(); + assertFalse(moduleID.equals(metaDataFromUI.get(middleName).get("moduleID"))); + } + } + // Close module + GeneralUIUtils.clickOnElementByText(moduleRowText); + } + } + + public static String convertAmdocsCsarGroupNameToSdcCsarGroupName(String originalString) { + return originalString.replace(PART_TO_REPLACE, ""); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ErrorMessageUIVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ErrorMessageUIVerificator.java new file mode 100644 index 0000000000..947a133e13 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ErrorMessageUIVerificator.java @@ -0,0 +1,62 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.enums.ErrorInfo; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.onap.sdc.frontend.ci.tests.datatypes.ErrorMessageProperties; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.testng.Assert; + +public class ErrorMessageUIVerificator { + + private static ErrorMessageProperties getErrorByType(ActionStatus errorType) { + try { + ErrorInfo errorInfo = ErrorValidationUtils.parseErrorConfigYaml(errorType.name()); + String messageId = errorInfo.getMessageId(); + String code = errorInfo.getCode().toString(); + + return new ErrorMessageProperties(messageId, code); + } catch (Exception e) { + return null; + } + } + + public static void validateErrorMessage(ActionStatus errorMessage) { + String errorMessageBox = null; + try { + //errorMessageBox = GeneralUIUtils.getWebElementByClassName("w-sdc-modal-caption").getText(); + errorMessageBox = GeneralUIUtils.getWebElementByClassName("error-message-component").getText(); + } catch (Exception e) { + ExtentTestActions.log(Status.INFO, "Did not find an error message popup."); + Assert.fail("Did not find an error message popup."); + } + + ExtentTestActions.log(Status.INFO, "An error message raised, validating its content."); + ErrorMessageProperties expectedResponseError = getErrorByType(errorMessage); + Assert.assertTrue(errorMessageBox.contains(expectedResponseError.getCode()), "Error message code is not " + expectedResponseError.getCode()); + Assert.assertTrue(errorMessageBox.contains(expectedResponseError.getMessageId()), "Error message ID is not " + expectedResponseError.getMessageId()); + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PortMirroringVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PortMirroringVerificator.java new file mode 100644 index 0000000000..c2da10d281 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PortMirroringVerificator.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.PortMirroringEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.PortMirroringUtils; +import org.openqa.selenium.By; + +import java.awt.datatransfer.UnsupportedFlavorException; +import java.io.IOException; + +import static org.testng.Assert.assertTrue; + +public class PortMirroringVerificator { + + private PortMirroringVerificator() { + } + + public static void checkProxyServiceName(String serviceName, String instanceId) { + String serviceActualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText(); + String serviceExpectedName = PortMirroringUtils.createproxyinstanceservicename(serviceName, instanceId); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the instance name is %s", serviceExpectedName)); + assertTrue(serviceActualName.equalsIgnoreCase(serviceExpectedName)); + } + + public static void checkProxyServiceType() { + String serviceActualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanelGeneralInfo.TYPE.getValue()).getText(); + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying the instance type is Service Proxy"); + assertTrue(serviceActualName.equalsIgnoreCase(PortMirroringEnum.SERVICE_PROXY_TYPE.getValue())); + } + + public static void validatingProxyServiceNameAndType(String serviceName, String instanceId) { + checkProxyServiceName(serviceName, instanceId); + checkProxyServiceType(); + } + + public static void validateGeneralInfo() { + String type = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanelGeneralInfo.TYPE.getValue()).getText(); + String resourceType = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanelGeneralInfo.RESOURCE_TYPE.getValue()).getText(); + String category = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanelGeneralInfo.CATEGORY.getValue()).getText(); + String subCategory = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanelGeneralInfo.SUB_CATEGORY.getValue()).getText(); + + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the type equals %s", PortMirroringEnum.TYPE.getValue())); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the resource type equals %s", PortMirroringEnum.RESOURCE_TYPE.getValue())); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the category equals %s", PortMirroringEnum.CATEGORY.getValue())); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the sub category equals %s", PortMirroringEnum.SUB_CATEGORY.getValue())); + + assertTrue(type.equalsIgnoreCase(PortMirroringEnum.TYPE.getValue())); + assertTrue(resourceType.equalsIgnoreCase(PortMirroringEnum.RESOURCE_TYPE.getValue())); + assertTrue(category.equalsIgnoreCase(PortMirroringEnum.CATEGORY.getValue())); + assertTrue(subCategory.equalsIgnoreCase(PortMirroringEnum.SUB_CATEGORY.getValue())); + } + + public static void validateReqsAndCapsTabExist() { + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying tab reqs and caps exist for PMC element"); + GeneralUIUtils.getWebElementBy(By.xpath(DataTestIdEnum.CompositionRightPanel.REQS_AND_CAPS_TAB_XPATH.getValue())).click(); + } + + public static void validateElementName(String expectedName) { + String serviceActualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.CompositionRightPanel.COMPONENT_TITLE.getValue()).getText(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying the instance name is %s", expectedName)); + assertTrue(serviceActualName.equalsIgnoreCase(expectedName)); + } + + public static void validateLinkProperties() throws IOException, UnsupportedFlavorException { + SetupCDTest.getExtendTest().log(Status.INFO, "Validate Link properties values"); + String actualNetworkRole = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.NETWORK_ROLE_XPATH.getValue()); + String actualNfcType = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.NFC_TYPE_XPATH.getValue()); + String actualPpsCapacity = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.PPS_CAPACITY_XPATH.getValue()); + String actualNfType = GeneralUIUtils.getTextValueFromWebElementByXpath(PortMirroringEnum.NF_TYPE_XPATH.getValue()); + + assertTrue(actualNetworkRole.equalsIgnoreCase(PortMirroringEnum.NETWORK_ROLE_VALUE.getValue())); + assertTrue(actualNfcType.equalsIgnoreCase(PortMirroringEnum.NFC_TYPE_VALUE.getValue())); + assertTrue(actualPpsCapacity.equalsIgnoreCase(PortMirroringEnum.PPS_CAPACITY_VALUE.getValue())); + assertTrue(actualNfType.equalsIgnoreCase(PortMirroringEnum.NF_TYPE_VALUE.getValue())); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PropertiesAssignmentVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PropertiesAssignmentVerificator.java new file mode 100644 index 0000000000..8dcae5b0b2 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PropertiesAssignmentVerificator.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +public class PropertiesAssignmentVerificator { + + private PropertiesAssignmentVerificator() { + } + + public static void validateFilteredPropertiesCount(int propertiesCount, String propertyLocation) { + int actualPropertiesCount = GeneralUIUtils.getWebElementsListByContainsClassName(propertyLocation).size(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating. Expected properties count: %s , Actual: %s", propertiesCount, actualPropertiesCount)); + String errMsg = String.format("Properties amount not as expected, expected: %s ,Actual: %s", propertiesCount, actualPropertiesCount); + assertTrue(actualPropertiesCount == propertiesCount, errMsg); + } + + public static void validatePropertyValue(String expectedPropertyName, String expectedPropertyValue) { + String actualPropertyValue = GeneralUIUtils.getWebElementByTestID(expectedPropertyName).getAttribute("value"); + assertTrue(expectedPropertyValue.equals(actualPropertyValue), String.format("Validating the value of property/input %s. Expected: %s, Actual: %s ", expectedPropertyName, expectedPropertyValue, actualPropertyValue)); + } + + public static void validatePropertyValueIsNull(String expectedPropertyName) { + String actualPropertyValue = GeneralUIUtils.getWebElementByTestID(expectedPropertyName).getAttribute("value"); + assertNull(actualPropertyValue, String.format("Validating the value of property/input %s. Expected: empty, Actual: %s ", expectedPropertyName, actualPropertyValue)); + } + + public static void validateListPropertyValue(DataTestIdEnum.PropertiesAssignmentScreen prefix, String expectedPropertyName, String expectedPropertyValue, int index) { + String listElement = prefix.getValue() + expectedPropertyName + "." + String.valueOf(index); + String actualPropertyValue = GeneralUIUtils.getWebElementByTestID(listElement).getAttribute("value"); + assertTrue(expectedPropertyValue.equals(actualPropertyValue), String.format("Validating the %s list element value of property %s. Expected: %s, Actual: %s ", index, expectedPropertyName, expectedPropertyValue, actualPropertyValue)); + } + + public static void validateBooleanPropertyValue(String expectedPropertyName, String expectedPropertyValue) { + String actualPropertyValue = GeneralUIUtils.getSelectedElementFromDropDown(expectedPropertyName).getText(); + assertTrue(expectedPropertyValue.equals(actualPropertyValue), String.format("Validating the value of property %s. Expected: %s, Actual: %s ", expectedPropertyName, expectedPropertyValue, actualPropertyValue)); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PropertyVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PropertyVerificator.java new file mode 100644 index 0000000000..8c2202e559 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/PropertyVerificator.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.verificator; + +import org.onap.sdc.backend.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; + +import static org.testng.Assert.assertTrue; + +public class PropertyVerificator { + + + private PropertyVerificator() { + } + + public static void validateEditVFCPropertiesPopoverFields(PropertyTypeEnum propertyType) { + String propertyValue = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_VALUE.getValue()).getAttribute("value"); + String propertyDescription = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_DESCRIPTION.getValue()).getAttribute("value"); + assertTrue(propertyType.getUpdateValue().equals(propertyValue), String.format("Property Value of type %s. Expected: %s, Actual: %s ", propertyType.getType().toString(), propertyType.getUpdateValue(), propertyValue)); + assertTrue(propertyType.getUpdateDescription().equals(propertyDescription), String.format("Property Description of type %s. Expected: %s, Actual: %s ", propertyType.getType().toString(), propertyType.getUpdateDescription(), propertyDescription)); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ServiceVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ServiceVerificator.java new file mode 100644 index 0000000000..95fd25e521 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ServiceVerificator.java @@ -0,0 +1,360 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.onap.sdc.backend.ci.tests.datatypes.ComponentReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.ServiceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.CompositionPage; +import org.onap.sdc.frontend.ci.tests.pages.DeploymentPage; +import org.onap.sdc.frontend.ci.tests.pages.ServiceGeneralPage; +import org.onap.sdc.backend.ci.tests.utils.general.AtomicOperationUtils; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.GroupInstanceProperty; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Service; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum.PropertiesPopupEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.PropertyPopup; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.support.ui.Select; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Random; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import static org.testng.Assert.assertTrue; + +public class ServiceVerificator { + + private static final int SLEEP_TIME = 1000; + private static final int ARTIFACT_SECTION_OFFSET = 700; + + private ServiceVerificator() { + } + + public static void verifyNumOfComponentInstances(ComponentReqDetails component, String version, int numOfVFC, + User user) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifing the number of components on the canvas; should be %s", numOfVFC)); + String responseAfterDrag = null; + component.setVersion(version); + if (component instanceof ServiceReqDetails) { + responseAfterDrag = RestCDUtils.getService((ServiceReqDetails) component, user).getResponse(); + } else if (component instanceof ResourceReqDetails) { + responseAfterDrag = RestCDUtils.getResource((ResourceReqDetails) component, user).getResponse(); + } + int size = 0; + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + if(jsonResource.get("componentInstances")!= null){ + size = ((JSONArray) jsonResource.get("componentInstances")).size(); + assertTrue(size == numOfVFC, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size); + ExtentTestActions.log(Status.INFO, "The number of components on the canvas was verified."); + }else{ + assertTrue(false, "Expected number of componenet instances is " + numOfVFC + ", but actual is " + size); + } + } + + public static void verifyServiceUpdatedInUI(ServiceReqDetails service) { + assertTrue(service.getName().equals(ResourceGeneralPage.getNameText())); + assertTrue(service.getDescription().equals(ResourceGeneralPage.getDescriptionText())); + assertTrue(service.getCategory().equals(ServiceGeneralPage.getCategoryText())); + assertTrue(service.getServiceFunction().equals(ServiceGeneralPage.getServiceFunctionText())); + assertTrue(service.getNamingPolicy().equals(ServiceGeneralPage.getNamingPolicyText())); + for(String tag: ServiceGeneralPage.getTags()){ + assertTrue(service.getTags().contains(tag)); + } + assertTrue(service.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + public static void verifyServiceDeletedInUI(ServiceReqDetails service) throws InterruptedException { + Thread.sleep(1000); + List<WebElement> cardElements = GeneralUIUtils.getElementsByCSS(DataTestIdEnum.DashboardCardEnum.DASHBOARD_CARD.getValue()); + if (!(cardElements.isEmpty())){ + for (WebElement cardElement: cardElements){ + WebElement componentName = GeneralUIUtils.getElementfromElementByCSS(cardElement, + DataTestIdEnum.DashboardCardEnum.INFO_NAME.getValue()); + WebElement componentType = GeneralUIUtils.getElementfromElementByCSS(cardElement, + DataTestIdEnum.DashboardCardEnum.ASSET_TYPE_CSS.getValue()); + + String componentNameStr = componentName.getAttribute("textContent").trim(), + componentTypeStr = componentType.getAttribute("class"); + + if (componentTypeStr.equals("S")) { + assertTrue(!(componentNameStr.equals(service.getName())), "Deleted service was found !!!"); + } + } + } + } + + public static void verifyServiceLifecycle(ServiceReqDetails service, User user, LifecycleStateEnum expectedLifecycleState) { + String responseAfterDrag = RestCDUtils.getService(service, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String actualLifecycleState = jsonResource.get("lifecycleState").toString(); + assertTrue(expectedLifecycleState.name().equals(actualLifecycleState), "actual: " + actualLifecycleState + "-- expected: " + expectedLifecycleState); + } + + public static void verifyServiceLifecycleInUI(LifeCycleStateEnum lifecycleState) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verfiying that service state is %s", lifecycleState.getValue())); + GeneralUIUtils.ultimateWait(); + assertTrue(ResourceGeneralPage.getLifeCycleState().equals(lifecycleState.getValue())); + } + + public static void verifyLinkCreated(ServiceReqDetails createServiceInUI, User user, int expectedRelationsSize) { + String responseAfterDrag = RestCDUtils.getService(createServiceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + assertTrue(((JSONArray) jsonResource.get("componentInstancesRelations")).size() == expectedRelationsSize); + + } + + public static void verifyManagmentWorkflow(String expectedName, String expectedDescription) { + String actualName = GeneralUIUtils.getWebElementBy(By.cssSelector("div[class='text name']")).getText(); + String actualDescription = GeneralUIUtils.getWebElementBy(By.cssSelector("div[class='text description']")).getText(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifing name ( should be %s ) and description ( should be %s ) ", expectedName, expectedDescription)); + assertTrue(actualName.equals(expectedName) && actualDescription.equals(expectedDescription)); + } + + public static void verifyVersionUI(String expected) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying that version is %s", expected)); + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum. + GeneralElementsEnum.VERSION_HEADER.getValue()).getText().replace("V", ""); + assertTrue(actualVersion.equals(expected), String.format("Expected version: %s, Actual version: %s", expected, actualVersion)); + } + + public static void verifyResourceInstanceVersionUI(String expected) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying that instance version is %s", expected)); + List<WebElement> selectedVersion = GeneralUIUtils. + findElementsByXpath("//option[contains(@class,\"select-instance-version\") and contains (@selected, \"selected\")]"); + String actual = selectedVersion.get(0).getText(); + assertTrue(expected.equals(actual), String.format("Expected version: %s, Actual version: %s", expected, actual)); + } + + public static void verifyOpenTabTitle(DataTestIdEnum.CompositionScreenEnum currentTab) throws Exception { + List<String> expectedTitles = new ArrayList<String>(); + for (String expectedTitle : currentTab.getTitle()) { + expectedTitles.add(expectedTitle.toLowerCase()); + } + for (WebElement actualTitle : CompositionPage.getOpenTabTitle()) { + int indexOfTitle = expectedTitles.indexOf(actualTitle.getText().trim().toLowerCase()); + assertTrue(indexOfTitle >= 0, "Wrong title"); + expectedTitles.remove(indexOfTitle); + } + assertTrue(expectedTitles.size() == 0, "Missing titles in " + currentTab.getValue()); + } + + public static void verifyDeploymentPageSubElements(String moduleName, DeploymentViewVerificator verificatorObj) throws Exception { + + HashMap<String, List<String>> moduleProperties = verificatorObj.getDeploymentViewData().get(moduleName); + + ServiceVerificator.moveMetadataPropertiesArtifactSection(-ARTIFACT_SECTION_OFFSET); + + List<WebElement> artifacts, properties; + artifacts = DeploymentPage.getArtifactNames(); + properties = DeploymentPage.getPropertyNames(); + assertTrue(moduleProperties.get("artifacts").size() == artifacts.size(), "Artifacts amount not as expected, expected " + moduleProperties.get("artifacts").size()); + assertTrue(moduleProperties.get("artifacts").containsAll(artifacts.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + assertTrue(moduleProperties.get("properties").size() == properties.size(), "Properties amount not as expected, expected " + moduleProperties.get("properties").size()); + assertTrue(moduleProperties.get("properties").containsAll(properties.stream(). + map(e -> e.getAttribute("textContent")). + collect(Collectors.toList()))); + + DeploymentPage.clickOnProperties(); + DeploymentPage.clickOnArtifacts(); + ServiceVerificator.moveMetadataPropertiesArtifactSection(ARTIFACT_SECTION_OFFSET); + } + + public static void verifyVFModuleCustomizationUUID(ServiceReqDetails service) throws Exception { + final int UUIDMinimalLength = 35; + Predicate<String> componentInstancePredicate = e -> e.length() > UUIDMinimalLength; + List<String> customizationUUIDList = getAllVFModuleCustomizationUUIDs(service); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating vfModuleCustomizationUUID uniqness ... ")); + assertTrue(customizationUUIDList.stream().allMatch(componentInstancePredicate), "vfModuleCustomizationUUID is less then 35 chars"); + CustomizationUUIDVerificator.validateCustomizationUUIDuniqueness(customizationUUIDList); + } + + public static List<String> getAllVFModuleCustomizationUUIDs(ServiceReqDetails service) throws Exception { + Service serviceObj = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service.getName(), service.getVersion()); + List<String> customizationUUIDList = serviceObj.getComponentInstances().get(0).getGroupInstances().stream(). + map(e -> e.getCustomizationUUID()). + collect(Collectors.toList()); + + return customizationUUIDList; + } + + public static String getVFModulePropertyValue(ServiceReqDetails service, String propertyName, String moduleName) throws Exception { + Service serviceObj = AtomicOperationUtils.getServiceObjectByNameAndVersion(UserRoleEnum.DESIGNER, service.getName(), service.getVersion()); + List<GroupInstance> groupInstances = serviceObj.getComponentInstances().get(0).getGroupInstances(); + List<GroupInstanceProperty> groupInstancesProperties = groupInstances.stream(). + filter(e -> e.getName().equals(moduleName)). + findFirst(). + get(). + convertToGroupInstancesProperties(); + String propertyValue = groupInstancesProperties.stream(). + filter(e -> e.getName().equals(propertyName)). + findFirst(). + get(). + getValue(); + return propertyValue; + } + + public static boolean isEqualCustomizationUUIDsAfterChanges(List<String> listBefore, List<String> listAfter) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating if vfModuleCustomizationUUID changed after certification ... ")); + return (listBefore.size() == listAfter.size()) && (listBefore.containsAll(listAfter)); + } + + public static void verifyDisabledServiceProperties() throws Exception { + List<String> propertiesForCheck = Arrays.asList("isBase", "vf_module_type", "vf_module_label", "vf_module_description"); + List<PropertiesPopupEnum> popupElementsForCheck = Arrays.asList(PropertiesPopupEnum.PROPERTY_NAME, + PropertiesPopupEnum.PROPERTY_DESCRIPTION, + PropertiesPopupEnum.PROPERTY_TYPE, + PropertiesPopupEnum.PROPERTY_VALUE); + ServiceVerificator.moveMetadataPropertiesArtifactSection(-ARTIFACT_SECTION_OFFSET); + List<WebElement> properties = DeploymentPage.getPropertyNames(); + + for (WebElement property : properties) { + if (propertiesForCheck.contains(property.getAttribute("textContent"))) { + DeploymentPage.clickOnProperty(property); + Select propertTypeElement = new Select(GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_TYPE.getValue())); + boolean isTypeBoolean = propertTypeElement.getFirstSelectedOption().getText().contains("boolean"); + for (PropertiesPopupEnum popupElement : popupElementsForCheck) { + if (isTypeBoolean && popupElement == PropertiesPopupEnum.PROPERTY_VALUE) { + assertTrue(GeneralUIUtils.checkForDisabledAttribute(DataTestIdEnum.PropertiesPopupEnum.PROPERTY_BOOLEAN_VALUE.getValue()), String.format("Element %s not disabled ", property.getText())); + } else { + assertTrue(GeneralUIUtils.checkForDisabledAttribute(popupElement.getValue()), String.format("Element %s not disabled ", property.getText())); + } + } + new PropertyPopup().clickCancel(); + } + } + + DeploymentPage.clickOnProperties(); + ServiceVerificator.moveMetadataPropertiesArtifactSection(ARTIFACT_SECTION_OFFSET); + } + + public static void verifyEnabledServiceProperties() throws Exception { + List<String> propertiesForCheck = Arrays.asList("initial_count", "max_vf_module_instances", "min_vf_module_instances"); + + ServiceVerificator.moveMetadataPropertiesArtifactSection(-ARTIFACT_SECTION_OFFSET); + List<WebElement> properties = DeploymentPage.getPropertyNames(); + + ServiceVerificator.positiveFlow(propertiesForCheck, properties); + ServiceVerificator.negativeFlow(propertiesForCheck, properties); + + DeploymentPage.clickOnProperties(); + ServiceVerificator.moveMetadataPropertiesArtifactSection(ARTIFACT_SECTION_OFFSET); + } + + public static void positiveFlow(List<String> propertiesForCheck, List<WebElement> properties) + throws InterruptedException { + final int randomInteger = 100; + int baseNumber = new Random().nextInt(randomInteger) + 2; + for (WebElement property : properties) { + String propertyName = property.getAttribute("textContent"); + if (propertiesForCheck.contains(propertyName)) { + DeploymentPage.clickOnProperty(property); + int actualNumber = 0; + if (propertyName.equals("initial_count")) { + actualNumber = baseNumber; + } else if (propertyName.equals("max_vf_module_instances")) { + actualNumber = baseNumber + 1; + } else if (propertyName.equals("min_vf_module_instances")) { + actualNumber = baseNumber - 1; + } + + new PropertyPopup().insertPropertyDefaultValue(String.valueOf(actualNumber)); + new PropertyPopup().clickSave(); + assertTrue(DeploymentPage.getPropertyValueFromPropertiesList(propertyName).equals(String.valueOf(actualNumber))); + } + } + } + + public static void negativeFlow(List<String> propertiesForCheck, List<WebElement> properties) + throws Exception { + int currentMaxValue = Integer.valueOf(DeploymentPage.getPropertyValueFromPropertiesList("max_vf_module_instances")); + int currentMinValue = Integer.valueOf(DeploymentPage.getPropertyValueFromPropertiesList("min_vf_module_instances")); + int currentInitialValue = Integer.valueOf(DeploymentPage.getPropertyValueFromPropertiesList("initial_count")); + PropertyPopup propertyPopupObj = new PropertyPopup(); + + for (WebElement property : properties) { + String propertyName = property.getAttribute("textContent"); + if (propertiesForCheck.contains(propertyName)) { + DeploymentPage.clickOnProperty(property); + if (propertyName.equals("initial_count")) { + + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMaxValue + 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMinValue - 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(0)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + + } else if (propertyName.equals("max_vf_module_instances")) { + + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentInitialValue - 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMinValue - 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(0)); + verifyErrorPresentAndSaveDisabled(); + + } else if (propertyName.equals("min_vf_module_instances")) { + + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentInitialValue + 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + propertyPopupObj.insertPropertyDefaultValue(String.valueOf(currentMaxValue + 1)); + ServiceVerificator.verifyErrorPresentAndSaveDisabled(); + } + + new PropertyPopup().clickCancel(); + } + } + } + + public static void verifyErrorPresentAndSaveDisabled() throws Exception { + assertTrue(DeploymentPage.isPropertySaveButtonDisabled(), "Property Save button enabled, should be disabled"); + assertTrue(DeploymentPage.getPropertyErrorValidationMessdge().size() == 1, "Error msg missing for input"); + } + + public static void moveMetadataPropertiesArtifactSection(int offset) throws InterruptedException { + WebElement dragLineElement = GeneralUIUtils.getElementByCSS("div.rg-top"); + GeneralUIUtils.dragAndDropElementByY(dragLineElement, offset); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ToscaValidation.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ToscaValidation.java new file mode 100644 index 0000000000..36eab13c77 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/ToscaValidation.java @@ -0,0 +1,605 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019 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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import fj.data.Either; +import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; +import org.onap.sdc.toscaparser.api.Group; +import org.onap.sdc.toscaparser.api.Property; +import org.onap.sdc.toscaparser.api.elements.Metadata; +import org.onap.sdc.toscaparser.api.parameters.Input; +import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaGroupPropertyDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaInputsTopologyTemplateDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaServiceGroupsMetadataDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.VfModuleDefinition; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class ToscaValidation { + + + private ToscaValidation() { + } + + /** + * @param expectedToscaDefinition - expected toscaDefinition object + * @param actualToscaDefinition - actual toscaDefinition object + * @return true if all validation success else return error map + */ + public static Either<Boolean, Map<String, Object>> resourceToscaMetadataValidator(ToscaDefinition expectedToscaDefinition, ToscaDefinition actualToscaDefinition) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate resource TOSCA metadata..."); + Map<String, String> expectedMetadata = expectedToscaDefinition.getMetadata(); + Map<String, String> actualMetadata = actualToscaDefinition.getMetadata(); + Either<Boolean, Map<String, Object>> resourceToscaMetadataValidator = compareStringMapData(expectedMetadata, actualMetadata); + if (resourceToscaMetadataValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Resource TOSCA metadata verification success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Resource TOSCA metadata verification failed" + resourceToscaMetadataValidator.right().value()); + } + return resourceToscaMetadataValidator; + } + + public static Boolean resourceToscaNodeTemplateMetadataValidator(Map<String, Map<String, String>> expectedMetadata, ToscaDefinition actualToscaDefinition) { + boolean isTestFailed = true; + for (String nodeTemplateName : expectedMetadata.keySet()) { + Either<Boolean, Map<String, Object>> serviceToscaMetadataValidator = componentToscaNodeTemplateMetadataValidator(expectedMetadata.get(nodeTemplateName), actualToscaDefinition, nodeTemplateName, ComponentTypeEnum.RESOURCE, nodeTemplateName); + if (!serviceToscaMetadataValidator.left().value()) { + isTestFailed = false; + } + } + return isTestFailed; + } + + public static Either<Boolean, Map<String, Object>> vfModuleJsonFileValidator(Map<String, VfModuleDefinition> expectedVfModulesDefinitionObject, Map<String, VfModuleDefinition> actualVfModulesDefinitionObject) { + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate vf module json file..."); + Either<Boolean, Map<String, Object>> vfModuleFileValidator = compareObjectMapData(expectedVfModulesDefinitionObject, actualVfModulesDefinitionObject); + if (vfModuleFileValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Vf module json file verification success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Vf module json file verification failed" + vfModuleFileValidator.right().value().toString()); + } + return vfModuleFileValidator; + } + + public static Either<Boolean, Map<String, Object>> serviceToscaMetadataValidator(Map<String, String> expectedMetadata, ToscaDefinition actualToscaDefinition) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA metadata..."); + Map<String, String> actualMetadata = actualToscaDefinition.getMetadata(); + Either<Boolean, Map<String, Object>> serviceToscaMetadataValidator = compareStringMapData(expectedMetadata, actualMetadata); + if (serviceToscaMetadataValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA metadata verification success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA metadata verification failed" + serviceToscaMetadataValidator.right().value().toString()); + } + return serviceToscaMetadataValidator; + } + + public static Either<Boolean, Map<String, Object>> serviceToscaGroupMetadataValidator(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, ToscaDefinition actualToscaDefinition) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group metadata..."); + Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups = actualToscaDefinition.getTopology_template().getGroups(); + Either<Boolean, Map<String, Object>> serviceToscaGroupMetadataValidator = compareServiceGroupMetadata(expectedServiceGroup, actualServiceGroups); + if (serviceToscaGroupMetadataValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group metadata verification success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group metadata verification failed" + serviceToscaGroupMetadataValidator.right().value().toString()); + } + return serviceToscaGroupMetadataValidator; + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupMetadata(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups) { + + Map<String, Object> errorMap = new HashMap<>(); + for (String groupName : expectedServiceGroup.keySet()) { + if (actualServiceGroups.get(groupName) == null) { + errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml"); + } else { + compareServiceGroupData(expectedServiceGroup.get(groupName), actualServiceGroups.get(groupName), groupName, errorMap); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupData(ToscaServiceGroupsMetadataDefinition expectedServiceGroupMetadata, ToscaServiceGroupsMetadataDefinition actualServiceGroupMetadata, String groupName, Map<String, Object> errorMap) { + + Field[] declaredFields = expectedServiceGroupMetadata.getClass().getSuperclass().getFields(); + for (Field field : declaredFields) { + if (!field.getName().equals("serialVersionUID")) { + try { + String expectedValue = (String) field.get(expectedServiceGroupMetadata); + String actualValue = (String) field.get(actualServiceGroupMetadata); + comparingServiceGroupMetadata(groupName, errorMap, field, expectedValue, actualValue); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + + // ###########################UsingParser############################ + public static Either<Boolean, Map<String, Object>> serviceToscaGroupMetadataValidatorUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group metadata..."); + Either<Boolean, Map<String, Object>> serviceToscaGroupMetadataValidator = compareServiceGroupMetadataUsingParser(expectedServiceGroup, actualServiceGroups); + if (serviceToscaGroupMetadataValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group metadata verification vs. tosca parser success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group metadata verification vs. tosca parser failed" + serviceToscaGroupMetadataValidator.right().value().toString()); + } + return serviceToscaGroupMetadataValidator; + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupMetadataUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups) { + + Map<String, Object> errorMap = new HashMap<>(); + for (String groupName : expectedServiceGroup.keySet()) { + Group actualGroup = getServiceToscaParserGroupFromObject(groupName, actualServiceGroups); + if (actualGroup == null) { + errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml"); + } else { + compareServiceGroupDataUsingParser(expectedServiceGroup.get(groupName), actualGroup.getMetadata(), groupName, errorMap); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static Group getServiceToscaParserGroupFromObject(String groupName, List<Group> actualServiceGroups) { + for (Group group : actualServiceGroups) { + if (group.getName().equals(groupName)) { + return group; + } + } + return null; + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupDataUsingParser(ToscaServiceGroupsMetadataDefinition expectedServiceGroupMetadata, Metadata actualServiceGroupMetadata, String groupName, Map<String, Object> errorMap) { + + Field[] declaredFields = expectedServiceGroupMetadata.getClass().getSuperclass().getFields(); + for (Field field : declaredFields) { + if (!field.getName().equals("serialVersionUID")) { + try { + String expectedValue = (String) field.get(expectedServiceGroupMetadata); + String actualValue = actualServiceGroupMetadata.getValue(field.getName()); + comparingServiceGroupMetadata(groupName, errorMap, field, expectedValue, actualValue); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static void comparingServiceGroupMetadata(String groupName, Map<String, Object> errorMap, Field field, String expectedValue, String actualValue) { + if (expectedValue != null && !expectedValue.trim().equals("")) { + if (actualValue != null) { + Boolean result = compareStringValue(expectedValue, actualValue); + if (!result) { + errorMap.put("Data field [" + field.getName() + "] in group service metadata [" + groupName + "]", "expected: " + expectedValue + ", actual: " + actualValue); + } + } else { + errorMap.put("Data field [" + field.getName() + "] in group service metadata [" + groupName + "]", " does not exist in actual object"); + System.out.println("Data field [" + field.getName() + "] in group service metadata [" + groupName + "] does not exist in actual object"); + } + } + } + +//############################################################################################ + + + // ###########################Property UsingParser############################ + public static Either<Boolean, Map<String, Object>> serviceToscaGroupPropertyValidatorUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group property..."); + Either<Boolean, Map<String, Object>> serviceToscaGroupMetadataValidator = compareServiceGroupPropertyUsingParser(expectedServiceGroup, actualServiceGroups); + if (serviceToscaGroupMetadataValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group property verification vs. tosca parser success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group property verification vs. tosca parser failed" + serviceToscaGroupMetadataValidator.right().value().toString()); + } + return serviceToscaGroupMetadataValidator; + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupPropertyUsingParser(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, List<Group> actualServiceGroups) { + + Map<String, Object> errorMap = new HashMap<>(); + for (String groupName : expectedServiceGroup.keySet()) { + Group actualGroup = getServiceToscaParserGroupFromObject(groupName, actualServiceGroups); + if (actualGroup == null) { + errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml"); + } else { + compareServiceGroupPropertyUsingParser(expectedServiceGroup.get(groupName).getProperties(), actualGroup.getProperties(), groupName, errorMap); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupPropertyUsingParser(ToscaGroupPropertyDefinition expectedServiceGroupProperty, LinkedHashMap<String, Property> actualServiceGroupProperty, String groupName, Map<String, Object> errorMap) { + + Field[] declaredFields = expectedServiceGroupProperty.getClass().getDeclaredFields(); + for (Field field : declaredFields) { + if (!field.getName().equals("serialVersionUID")) { + try { + String expectedValue = null; + String actualValue = null; + if (field.get(expectedServiceGroupProperty) != null) { + expectedValue = field.get(expectedServiceGroupProperty).toString(); + } + if (actualServiceGroupProperty.get(field.getName()) != null && actualServiceGroupProperty.get(field.getName()).getValue() != null) { + actualValue = actualServiceGroupProperty.get(field.getName()).getValue().toString(); + } + comparingServiceGroupProperty(groupName, errorMap, field, expectedValue, actualValue); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + +//############################################################################################ + + + //?------- + public static Either<Boolean, Map<String, Object>> serviceToscaGroupPropertyValidator(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, ToscaDefinition actualToscaDefinition) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA group property..."); + Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups = actualToscaDefinition.getTopology_template().getGroups(); + Either<Boolean, Map<String, Object>> serviceToscaGroupPropertyValidator = compareServiceGroupProperty(expectedServiceGroup, actualServiceGroups); + if (serviceToscaGroupPropertyValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA group property verification success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA group property verification failed" + serviceToscaGroupPropertyValidator.right().value().toString()); + } + return serviceToscaGroupPropertyValidator; + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupProperty(Map<String, ToscaGroupsTopologyTemplateDefinition> expectedServiceGroup, Map<String, ToscaGroupsTopologyTemplateDefinition> actualServiceGroups) { + + Map<String, Object> errorMap = new HashMap<>(); + for (String groupName : expectedServiceGroup.keySet()) { + if (actualServiceGroups.get(groupName) == null) { + errorMap.put("group/module [" + groupName + "]", " does not exist in TOSCA main yaml"); + } else { + compareServiceGroupProperty(expectedServiceGroup.get(groupName).getProperties(), actualServiceGroups.get(groupName).getProperties(), groupName, errorMap); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static Either<Boolean, Map<String, Object>> compareServiceGroupProperty(ToscaGroupPropertyDefinition expectedServiceGroupProperty, ToscaGroupPropertyDefinition actualServiceGroupProperty, String groupName, Map<String, Object> errorMap) { + + Field[] declaredFields = expectedServiceGroupProperty.getClass().getDeclaredFields(); + for (Field field : declaredFields) { + if (!field.getName().equals("serialVersionUID")) { + try { + String expectedValue = null; + String actualValue = null; + if (field.get(expectedServiceGroupProperty) != null) { + expectedValue = field.get(expectedServiceGroupProperty).toString(); + } + if (field.get(actualServiceGroupProperty) != null) { + actualValue = field.get(actualServiceGroupProperty).toString(); + } + comparingServiceGroupProperty(groupName, errorMap, field, expectedValue, actualValue); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + } + + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static void comparingServiceGroupProperty(String groupName, Map<String, Object> errorMap, Field field, String expectedValue, String actualValue) { + if (expectedValue != null && !expectedValue.trim().equals("")) { + if (actualValue != null) { + Boolean result = compareStringValue(expectedValue, actualValue); + if (!result) { + errorMap.put("Data field [" + field.getName() + "] in group service property [" + groupName + "]", "expected: " + expectedValue + ", actual: " + actualValue); + } + } else { + errorMap.put("Data field [" + field.getName() + "] in group service property [" + groupName + "]", " does not exist in actual object"); + System.out.println("Data field [" + field.getName() + "] in group service property [" + groupName + "] does not exist in actual object"); + } + } + } + + + // ---------------------------------- + public static Either<Boolean, Map<String, Object>> componentToscaNodeTemplateMetadataValidator(Map<String, String> expectedMetadata, ToscaDefinition actualToscaDefinition, String nodeTemplateName, ComponentTypeEnum componentType, String componentName) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate " + componentName + " " + componentType.getValue() + " node template TOSCA metadata..."); + Map<String, String> actualMetadata = actualToscaDefinition.getTopology_template().getNode_templates().get(nodeTemplateName).getMetadata(); + Either<Boolean, Map<String, Object>> componentToscaMetadataValidator = compareStringMapData(expectedMetadata, actualMetadata); + if (componentToscaMetadataValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, " " + componentName + " " + componentType.getValue() + "TOSCA node template metadata verification success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, " " + componentName + " " + componentType.getValue() + "TOSCA node template metadata verification failed" + componentToscaMetadataValidator.right().value().toString()); + } + return componentToscaMetadataValidator; + } + + public static Either<Boolean, Map<String, Object>> serviceToscaMetadataValidatorAgainstParser(Map<String, String> expectedMetadata, Metadata actualMetadata) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate service TOSCA metadata..."); + + Either<Boolean, Map<String, Object>> serviceToscaMetadataValidator = compareMetadataUsingToscaParser(expectedMetadata, actualMetadata); + if (serviceToscaMetadataValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "Service TOSCA metadata verification vs. tosca parser success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "Service TOSCA metadata verification vs. tosca parser failed" + serviceToscaMetadataValidator.right().value().toString()); + } + return serviceToscaMetadataValidator; + } + + + private static Either<Boolean, Map<String, Object>> compareStringMapData(Map<String, String> expectedMetadata, Map<String, String> actualMetadata) { + Either.left(false); + Map<String, Object> errorMap = new HashMap<>(); + for (String key : expectedMetadata.keySet()) { + boolean isError = compareStringValue(expectedMetadata.get(key), actualMetadata.get(key)); + if (!isError) { + errorMap.put("Data key[" + key + "]", "expected: " + expectedMetadata.get(key) + ", actual: " + actualMetadata.get(key)); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + + private static Either<Boolean, Map<String, Object>> compareObjectMapData(Map<String, VfModuleDefinition> expectedObject, Map<String, VfModuleDefinition> actualObject) { + Map<String, Object> errorMap = new HashMap<>(); + for (String key : expectedObject.keySet()) { + boolean isError = compareObjectValue(expectedObject.get(key), actualObject.get(key)); + if (!isError) { + errorMap.put("Data key[" + key + "]", "expected: " + expectedObject.get(key) + ", actual: " + actualObject.get(key)); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static boolean compareObjectValue(VfModuleDefinition expected, VfModuleDefinition actual) { + return expected.equals(actual); + } + + private static Either<Boolean, Map<String, Object>> compareMetadataUsingToscaParser(Map<String, String> expectedMetadata, Metadata actualMetadata) { + Map<String, Object> errorMap = new HashMap<>(); + for (String key : expectedMetadata.keySet()) { + boolean isError = compareStringValue(expectedMetadata.get(key), actualMetadata.getValue(key)); + if (!isError) { + errorMap.put("Data key[" + key + "]", "expected: " + expectedMetadata.get(key) + ", actual: " + actualMetadata.getValue(key)); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static boolean compareStringValue(String expected, String actual) { + return expected.equals(actual); + } + + public static Either<Boolean, Map<String, Object>> toscaInputsValidator(Map<String, ToscaInputsTopologyTemplateDefinition> expectedInputs, Map<String, ToscaInputsTopologyTemplateDefinition> actualInputs) { + + SetupCDTest.getExtendTest().log(Status.INFO, "Going to validate TOSCA inputs..."); + Either<Boolean, Map<String, Object>> toscaInputsValidator = compareInputs(expectedInputs, actualInputs); + if (toscaInputsValidator.isLeft()) { + SetupCDTest.getExtendTest().log(Status.INFO, "TOSCA inputs verification success"); + } else { + SetupCDTest.getExtendTest().log(Status.ERROR, "TOSCA inputs verification failed" + toscaInputsValidator.right().value().toString()); + } + + if (toscaInputsValidator.right() != null && !toscaInputsValidator.right().equals("")) { + return toscaInputsValidator; + } + return Either.left(true); + } + + private static Either<Boolean, Map<String, Object>> compareInputs(Map<String, ToscaInputsTopologyTemplateDefinition> expectedInputs, Map<String, ToscaInputsTopologyTemplateDefinition> actualInputs) { + + Map<String, Object> errorMap = new HashMap<>(); + + for (String inputName : expectedInputs.keySet()) { + if (actualInputs.get(inputName) == null) { + errorMap.put("input [" + inputName + "]", " does not exist in TOSCA main yaml"); + } else { + compareInputData(expectedInputs.get(inputName), actualInputs.get(inputName), errorMap); + } + } + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static Either<Boolean, Map<String, Object>> compareInputData(ToscaInputsTopologyTemplateDefinition expectedInputDefinition, ToscaInputsTopologyTemplateDefinition actualInputDefinition, Map<String, Object> errorMap) { + + Field[] declaredFields = expectedInputDefinition.getClass().getDeclaredFields(); + for (Field field : declaredFields) { + try { + Object expectedValue = field.get(expectedInputDefinition); + Object actualValue = field.get(actualInputDefinition); +// verification exclude fields as (immutable, hidden, constraints, entry_schema) according Renana + if (expectedValue != null && !expectedValue.toString().trim().equals("") && field.getName() != "name" && field.getName() != "immutable" && field.getName() != "hidden" && field.getName() != "constraints" && field.getName() != "entry_schema" && field.getName() != "required") { + if (actualValue != null) { + compareInputValue(expectedInputDefinition, errorMap, field, expectedValue, actualValue); + } else { + errorMap.put("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]", " does not exist in actual object"); + System.out.println("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "] does not exist in actual object"); + } + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + + if (!errorMap.isEmpty()) { + return Either.right(errorMap); + } + return Either.left(true); + } + + private static void compareInputValue(ToscaInputsTopologyTemplateDefinition expectedInputDefinition, Map<String, Object> errorMap, Field field, Object expectedValue, Object actualValue) { + if (field.getName().equals("value") || field.getName().equals("Default")) { + switch (expectedInputDefinition.getType()) { + case "string": + if (!expectedValue.toString().replace("\n", " ").replaceAll("( +)", " ").equals(actualValue.toString().replace("\n", " ").replaceAll("( +)", " "))) { + errorMap.put("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]", "expected: " + expectedValue + ", actual: " + actualValue); + System.out.println("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]: expected: " + expectedValue + ", actual: " + actualValue); + } + break; + case "float": + float newExpectedValue = convertObjectToFloat(expectedValue); + float newActualValue = convertObjectToFloat(actualValue); + if (newExpectedValue != newActualValue) { + errorMap.put("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]", "expected: " + newExpectedValue + ", actual: " + newActualValue); + System.out.println("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]: expected: " + newExpectedValue + ", actual: " + newActualValue); + } + break; + case "boolean": + if (!expectedValue.toString().equalsIgnoreCase(actualValue.toString())) { + errorMap.put("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]", "expected: " + expectedValue + ", actual: " + actualValue); + System.out.println("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]: expected: " + expectedValue + ", actual: " + actualValue); + } + break; + case "list": + expectedInputDefinition.getEntry_schema().get("type"); + break; + case "map": + + break; + default: + break; + } + + + } else { + if (!expectedValue.equals(actualValue)) { + errorMap.put("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]", "expected: " + expectedValue + ", actual: " + actualValue); + System.out.println("Data field [" + field.getName() + "] in input [" + expectedInputDefinition.getName() + "]: expected: " + expectedValue + ", actual: " + actualValue); + } + } + + } + + + private static float convertObjectToFloat(Object object) { + + float floatValue = 0; + + if (object instanceof Integer) { + floatValue = ((Integer) object).floatValue(); + } + if (object instanceof Double) { + floatValue = ((Double) object).floatValue(); + } + if (object instanceof Float) { + floatValue = ((Float) object).floatValue(); + } + if (object instanceof String) { + floatValue = Float.parseFloat(object.toString()); + } + + if (object instanceof Long) { + floatValue = ((Long) object).floatValue(); + } + return floatValue; + } + + public static Either<Boolean, Map<String, Object>> toscaInputsValidatorAgainstParser(Map<String, ToscaInputsTopologyTemplateDefinition> expectedInputsMap, ISdcCsarHelper fdntCsarHelper) { + SetupCDTest.getExtendTest().log(Status.INFO, "Going to convert tosca parser inputs output to ToscaInputsTopologyTemplateDefinition object..."); + if (!fdntCsarHelper.getServiceInputs().isEmpty()) { + if (expectedInputsMap != null && !expectedInputsMap.isEmpty()) { + return Either.left(true); + } else { + Map<String, Object> errorMap = new HashMap<>(); + errorMap.put("Inputs", " do not exist on actual service"); + SetupCDTest.getExtendTest().log(Status.INFO, "Inputs do not exist on actual service csar"); + return Either.right(errorMap); + } + } + Map<String, ToscaInputsTopologyTemplateDefinition> actualInputsMap = convertInputsParserOutputToMap(fdntCsarHelper); + return toscaInputsValidator(expectedInputsMap, actualInputsMap); + } + + /** + * @param fdntCsarHelper convert list of inputs return from tosca parser to map of ToscaInputsTopologyTemplateDefinition + * @return field.get(actualServiceGroupProperty) + */ + private static Map<String, ToscaInputsTopologyTemplateDefinition> convertInputsParserOutputToMap(ISdcCsarHelper fdntCsarHelper) { + Map<String, ToscaInputsTopologyTemplateDefinition> actualInputsMap = new HashMap<>(); + List<Input> serviceInputs = fdntCsarHelper.getServiceInputs(); + for (Input input : serviceInputs) { + ToscaInputsTopologyTemplateDefinition actualInputDefinition = new ToscaInputsTopologyTemplateDefinition(); + actualInputDefinition.setDefault(input.getDefault()); + actualInputDefinition.setType(input.getType()); + actualInputDefinition.setDescription(input.getDescription()); + actualInputsMap.put(input.getName(), actualInputDefinition); + } + return actualInputsMap; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/UserManagementVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/UserManagementVerificator.java new file mode 100644 index 0000000000..7baac33225 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/UserManagementVerificator.java @@ -0,0 +1,148 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.apache.commons.lang3.text.WordUtils; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.frontend.ci.tests.pages.AdminGeneralPage; +import org.onap.sdc.backend.ci.tests.utils.validation.ErrorValidationUtils; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import java.util.Arrays; +import java.util.List; + +public class UserManagementVerificator { + + private UserManagementVerificator() { + } + + public static void validateUserCreated(String userId, UserRoleEnum role) { + + ExtentTestActions.log(Status.INFO, "Validating that a new user is created and displayed in the first row in the table."); + + final int firstRow = 0; + + WebElement actualFirstName = AdminGeneralPage.getUserManagementTab().getFirstName(firstRow); + WebElement actualLastName = AdminGeneralPage.getUserManagementTab().getLastName(firstRow); + WebElement actualUserId = AdminGeneralPage.getUserManagementTab().getUserId(firstRow); + WebElement actualEmail = AdminGeneralPage.getUserManagementTab().getEmail(firstRow); + WebElement actualRole = AdminGeneralPage.getUserManagementTab().getRole(firstRow); + WebElement actualLastActive = AdminGeneralPage.getUserManagementTab().getLastActive(firstRow); + + + String actualFirstNameText = actualFirstName.getText(); + String actualLastNameText = actualLastName.getText(); + String actualUserIdText = actualUserId.getText(); + String actualEmailText = actualEmail.getText(); + String actualRoleText = actualRole.getText(); + String actualLastActiveText = actualLastActive.getText(); + + Assert.assertTrue(actualFirstNameText.equals("---"), "Actual first name is not '---'."); + Assert.assertTrue(actualLastNameText.equals("---"), "Actual last name is not '---'."); + Assert.assertTrue(actualUserIdText.equals(userId), "Actual user id is not " + userId); + Assert.assertTrue(actualEmailText.equals("---"), "Actual email is not '---'."); + Assert.assertTrue(actualRoleText.equals(WordUtils.capitalize(role.name().toLowerCase())), "Actual role is not " + role.name()); + Assert.assertTrue(actualLastActiveText.equals("Waiting"), "Actual role is not 'Waiting'."); + } + + + public static void validateUserRoleUpdated(int rowIndx, UserRoleEnum updatedRole) { + ExtentTestActions.log(Status.INFO, "Validating role is updated to " + updatedRole.name() + " in UI."); + WebElement actualRole = AdminGeneralPage.getUserManagementTab().getRole(rowIndx); + String actualRoleText = actualRole.getText(); + Assert.assertTrue(actualRoleText.equals(WordUtils.capitalize(updatedRole.name().toLowerCase())), "Actual role is not " + updatedRole.name()); + } + + public static void validateUserRoleUpdatedViaRest(User reqUser, User user, UserRoleEnum expectedUserRole) { + try { + ExtentTestActions.log(Status.INFO, "Validating role is updated to " + expectedUserRole.name() + " in BE."); + String actualUserRole = RestCDUtils.getUserRole(reqUser, user); + Assert.assertTrue(expectedUserRole.name().toLowerCase().equals(actualUserRole.toLowerCase()), "User role is not updated."); + } catch (Exception e) { + Assert.fail("The actual user role is null"); + } + } + + public static void validateUserNotFoundViaRest(User reqUser, User user) { + try { + ExtentTestActions.log(Status.INFO, "Validating user " + reqUser.getUserId() + " is not found in BE."); + RestResponse getUserResp = RestCDUtils.getUser(reqUser, user); + ErrorValidationUtils.checkBodyResponseOnError(ActionStatus.USER_INACTIVE.name(), Arrays.asList(reqUser.getUserId()), getUserResp.getResponse()); + } catch (Exception e) { + Assert.fail("The response message does not describe the user is not found."); + } + } + + public static void validateUserIdNotFound(String userId) { + ExtentTestActions.log(Status.INFO, "Validating that user " + userId + " is not found."); + AdminGeneralPage.getUserManagementTab().searchUser(userId); + List<WebElement> rows = AdminGeneralPage.getUserManagementTab().getAllRowsDisplayed(); + Assert.assertEquals(rows.size(), 0, String.format("There are %s rows instead of none.", rows.size())); + } + + public static void validateOnlySingleRowDisplayed() { + ExtentTestActions.log(Status.INFO, "Validating that only a single row is displayed in table."); + List<WebElement> rows = AdminGeneralPage.getUserManagementTab().getAllRowsDisplayed(); + Assert.assertEquals(rows.size(), 1, String.format("There are %s rows instead of %s.", rows.size(), 1)); + } + + public static void validateRowDisplayedCorrectly(User user, int rowindex) { + String role = user.getRole(); + String userId = user.getUserId(); + String firstName = user.getFirstName(); + String lastName = user.getLastName(); + String email = user.getEmail(); + + ExtentTestActions.log(Status.INFO, "Validating that the row is properly displayed."); + + WebElement actualFirstName = AdminGeneralPage.getUserManagementTab().getFirstName(rowindex); + WebElement actualLastName = AdminGeneralPage.getUserManagementTab().getLastName(rowindex); + WebElement actualUserId = AdminGeneralPage.getUserManagementTab().getUserId(rowindex); + WebElement actualEmail = AdminGeneralPage.getUserManagementTab().getEmail(rowindex); + WebElement actualRole = AdminGeneralPage.getUserManagementTab().getRole(rowindex); + + + String actualFirstNameText = actualFirstName.getText(); + String actualLastNameText = actualLastName.getText(); + String actualUserIdText = actualUserId.getText(); + String actualEmailText = actualEmail.getText(); + String actualRoleText = actualRole.getText(); + + Assert.assertTrue(actualFirstNameText.equals(firstName), "Actual first name is not " + firstName); + Assert.assertTrue(actualLastNameText.equals(lastName), "Actual last name is not " + lastName); + Assert.assertTrue(actualUserIdText.equals(userId), "Actual user id is not " + userId); + Assert.assertTrue(actualEmailText.contains(email), "Actual email does not contain " + email); + Assert.assertTrue(actualRoleText.equals(WordUtils.capitalize(role.toLowerCase())), "Actual role is not " + role); + } + + public static void validateFirstRowDisplayedCorrectly(User user) { + validateRowDisplayedCorrectly(user, 0); + } + + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VFCArtifactVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VFCArtifactVerificator.java new file mode 100644 index 0000000000..f6d6353403 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VFCArtifactVerificator.java @@ -0,0 +1,347 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.apache.http.HttpStatus; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.onap.sdc.backend.ci.tests.datatypes.HeatMetaFirstLevelDefinition; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.openecomp.sdc.be.model.User; +import org.onap.sdc.frontend.ci.tests.datatypes.VFCArtifact; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.testng.Assert; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.testng.Assert.assertTrue; + +public class VFCArtifactVerificator { + + private VFCArtifactVerificator() { + } + + private static final String ARTIFACTS = "artifacts"; + private static final String DEPLOYMENT_ARTIFACTS = "deploymentArtifacts"; + private static List<VFCArtifact> vfcArtifactList = new ArrayList<VFCArtifact>(); + private static JSONObject jsonResource; + + public static void verifyVFCArtifactsNotInVFArtifactList(ResourceReqDetails resource, User user, RestResponse optionalGetResponse, Map<String, LinkedList<HeatMetaFirstLevelDefinition>> expectedArtifactMap) { + ExtentTestActions.log(Status.INFO, "Verifying that VFC artifacts are not as part of VF artifacts."); + LinkedList<HeatMetaFirstLevelDefinition> expectedDeploymentArtifacts = expectedArtifactMap.get(DEPLOYMENT_ARTIFACTS); + LinkedList<HeatMetaFirstLevelDefinition> expectedInformationalArtifacts = expectedArtifactMap.get(ARTIFACTS); + + Map<String, Object> vfDepArtifacts = getVFDeploymentArtifacts(resource, user, optionalGetResponse); + for (Object artifact : vfDepArtifacts.values()) { + JSONObject acArtifact = ((JSONObject) JSONValue.parse(artifact.toString())); + String acArtifactName = acArtifact.get("artifactName").toString(); + + for (HeatMetaFirstLevelDefinition exDepArtifact : expectedDeploymentArtifacts) { + assertTrue(!exDepArtifact.getType().equals(acArtifactName)); + } + } + + Map<String, Object> vfInfoArtifacts = getVFInforamtionalArtifacts(resource, user, optionalGetResponse); + for (Object artifact : vfInfoArtifacts.values()) { + JSONObject acArtifact = ((JSONObject) JSONValue.parse(artifact.toString())); + if (acArtifact.containsKey("artifactName")) { + String acArtifactName = acArtifact.get("artifactName").toString(); + + for (HeatMetaFirstLevelDefinition exInfoArtifact : expectedInformationalArtifacts) { + assertTrue(!exInfoArtifact.getType().equals(acArtifactName)); + } + } + + + } + + + } + + public static void verifyVfcArtifactUpdated(String instanceName, ResourceReqDetails resource, User user) { + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts are updated."); + List<VFCArtifact> vfcArtifactsBeforeUpdate = getVfcArtifactList(); + + setVfcArtifactList(new ArrayList<VFCArtifact>()); + setActualVfcArtifactList(instanceName, resource, user); + + for (VFCArtifact artifact : vfcArtifactsBeforeUpdate) { + String artifactnameBeforeUpdate = artifact.getArtifactname(); + for (VFCArtifact newArtifact : vfcArtifactList) { + String artifactnameAfterUpdate = newArtifact.getArtifactname(); + if (artifactnameBeforeUpdate.equals(artifactnameAfterUpdate)) { + String artifactUUIDAfterUpdate = newArtifact.getArtifactUUID(); + assertTrue(!artifactUUIDAfterUpdate.equals(artifact.getArtifactUUID())); + + int artifactVersionAfterUpdate = Integer.parseInt(newArtifact.getArtifactVersion()); + int artifactVersionBeforeUpdate = Integer.parseInt(artifact.getArtifactVersion()); + assertTrue(artifactVersionAfterUpdate == artifactVersionBeforeUpdate + 1); + + + vfcArtifactList.remove(newArtifact); + + ExtentTestActions.log(Status.INFO, "VFC artifacts are updated and verified."); + + break; + } + } + } + + + assertTrue(vfcArtifactList.size() == 0); + + } + + public static void verifyVFCArtifactNotChanged(String instanceName, ResourceReqDetails resource, User user) { + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts are not chaned after update."); + List<VFCArtifact> vfcArtifactsBeforeUpdate = getVfcArtifactList(); + + setVfcArtifactList(new ArrayList<VFCArtifact>()); + setActualVfcArtifactList(instanceName, resource, user); + + for (VFCArtifact artifact : vfcArtifactsBeforeUpdate) { + String artifactnameBeforeUpdate = artifact.getArtifactname(); + for (VFCArtifact newArtifact : vfcArtifactList) { + String artifactnameAfterUpdate = newArtifact.getArtifactname(); + if (artifactnameBeforeUpdate.equals(artifactnameAfterUpdate)) { + String artifactUUIDAfterUpdate = newArtifact.getArtifactUUID(); + assertTrue(artifactUUIDAfterUpdate.equals(artifact.getArtifactUUID())); + + int artifactVersionAfterUpdate = Integer.parseInt(newArtifact.getArtifactVersion()); + int artifactVersionBeforeUpdate = Integer.parseInt(artifact.getArtifactVersion()); + assertTrue(artifactVersionAfterUpdate == artifactVersionBeforeUpdate); + + vfcArtifactList.remove(newArtifact); + break; + } + } + } + + + assertTrue(vfcArtifactList.size() == 0); + + } + + public static void verifyNoVfcArtifacts(ResourceReqDetails resource, User user, RestResponse optionalGetResponse) { + ExtentTestActions.log(Status.INFO, "Verifying that there are no VFC artifacts at all."); + JSONArray jArr = getVFInstances(resource, user, optionalGetResponse); + for (Object instanceObj : jArr) { + JSONObject instance = (JSONObject) JSONValue.parse(instanceObj.toString()); + List<String> actualDeploymentArtifacts = getActualVfcInstanceArtifactsFromJson(DEPLOYMENT_ARTIFACTS, instance); + + assertTrue(actualDeploymentArtifacts == null || actualDeploymentArtifacts.size() == 0); + } + } + + public static void verifyVfcArtifacts(ResourceReqDetails resource, User user, String instanceName, Map<String, LinkedList<HeatMetaFirstLevelDefinition>> expectedArtifactMap, + RestResponse optionalGetResponse) { + ExtentTestActions.log(Status.INFO, "Verifying VFC artifacts for instance named " + instanceName); + + String exCompName = instanceName.split(".vfc.")[1].toLowerCase(); + String exName = instanceName.split(".heat.")[1].toLowerCase(); + + JSONArray jArr = getVFInstances(resource, user, optionalGetResponse); + int jArrSize = jArr.size(); + + for (Object instanceObj : jArr) { + JSONObject instance = (JSONObject) JSONValue.parse(instanceObj.toString()); + String componentName = instance.get("componentName").toString().toLowerCase(); + String name = instance.get("name").toString().toLowerCase(); + + if (componentName.contains(exCompName) || name.toLowerCase().equals(exName)) { + + List<String> actualDeploymentArtifacts = getActualVfcInstanceArtifactsFromJson(DEPLOYMENT_ARTIFACTS, instance); + LinkedList<HeatMetaFirstLevelDefinition> expectedDeploymentArtifacts = expectedArtifactMap.get(DEPLOYMENT_ARTIFACTS); + checkVFCArtifactsExist(expectedDeploymentArtifacts, actualDeploymentArtifacts); + + + List<String> actualInformationalArtifacts = getActualVfcInstanceArtifactsFromJson(ARTIFACTS, instance); + LinkedList<HeatMetaFirstLevelDefinition> expectedInformationalArtifacts = expectedArtifactMap.get(ARTIFACTS); + checkVFCArtifactsExist(expectedInformationalArtifacts, actualInformationalArtifacts); + + jArr.remove(instanceObj); + + ExtentTestActions.log(Status.INFO, "VFC artifacts for instance named " + instanceName + "are verified."); + + break; + } + } + + assertTrue(jArr.size() == jArrSize - 1, "Instance " + instanceName + " was not found and tested"); + + } + + + private static JSONArray getVFInstances(ResourceReqDetails resource, User user, RestResponse response) { + + jsonResource = getVFAsJsonObject(resource, user, response); + JSONArray jArr = (JSONArray) jsonResource.get("componentInstances"); + return jArr; + } + + private static Map<String, Object> getVFDeploymentArtifacts(ResourceReqDetails resource, User user, RestResponse response) { + + jsonResource = getVFAsJsonObject(resource, user, response); + Map<String, Object> jArr = (Map<String, Object>) jsonResource.get(DEPLOYMENT_ARTIFACTS); + return jArr; + } + + private static Map<String, Object> getVFInforamtionalArtifacts(ResourceReqDetails resource, User user, RestResponse response) { + + jsonResource = getVFAsJsonObject(resource, user, response); + Map<String, Object> jArr = (Map<String, Object>) jsonResource.get(ARTIFACTS); + return jArr; + } + + private static JSONObject getVFAsJsonObject(ResourceReqDetails resource, User user, RestResponse response) { + if (response == null) { + resource.setUniqueId(null); + response = RestCDUtils.getResource(resource, user); + assertTrue(response.getErrorCode().intValue() == HttpStatus.SC_OK); + getVFAsJsonObject(resource, user, response); + } + + String responseAfterDrag = response.getResponse(); + jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + return jsonResource; + } + + + private static List<String> getActualVfcInstanceArtifactsFromJson(String artifactKind, JSONObject instanceFromJson) { + Object actualtObject = instanceFromJson.get(artifactKind); + if (actualtObject != null) { + JSONObject actualJsonObject = (JSONObject) JSONValue.parse(actualtObject.toString()); + List<String> actualArtifacts = (List<String>) actualJsonObject.keySet().stream().map(e -> actualJsonObject.get(e).toString()).collect(Collectors.toList()); + return actualArtifacts; + } + return null; + } + + private static void checkVFCArtifactsExist(LinkedList<HeatMetaFirstLevelDefinition> expectedArtifacts, List<String> actualArtifacts) { + if (expectedArtifacts == null) { + return; + } + + if (expectedArtifacts.size() != actualArtifacts.size()) { + ExtentTestActions.log(Status.FAIL, "Expected and actual VFC artifacts lists size are not the same. Expected size: " + expectedArtifacts.size() + " , actual size: " + actualArtifacts.size()); + Assert.fail("Expected and actual VFC artifacts lists size are not the same. Expected size: " + expectedArtifacts.size() + " , actual size: " + actualArtifacts.size()); + } + + List<String> types = new ArrayList<String>(); + List<String> fileNames = new ArrayList<String>(); + for (HeatMetaFirstLevelDefinition exArtifact : expectedArtifacts) { + + fileNames.add(exArtifact.getFileName()); + types.add(exArtifact.getType()); + + } + + for (int i = 0; i < actualArtifacts.size(); i++) { + String actualArtifactsString = actualArtifacts.get(i); + JSONObject acArtifact = ((JSONObject) JSONValue.parse(actualArtifactsString)); + + String acArtifactFileName = acArtifact.get("artifactName").toString(); + String acArtifactType = acArtifact.get("artifactType").toString(); + + assertTrue(types.contains(acArtifactType), "List does not contain " + acArtifactType); + assertTrue(fileNames.contains(acArtifactFileName), "List does not contain " + acArtifactFileName); + + types.remove(acArtifactType); + fileNames.remove(acArtifactFileName); + + } + + assertTrue(types.size() == 0); + assertTrue(fileNames.size() == 0); + + } + + public static List<VFCArtifact> getVfcArtifactList() { + return vfcArtifactList; + } + + + public static void setVfcArtifactList(List<VFCArtifact> vfcArtifactList) { + VFCArtifactVerificator.vfcArtifactList = vfcArtifactList; + } + + public static void setActualVfcArtifactList(String instanceName, ResourceReqDetails resource, User user) { + String exCompName = instanceName.split(".vfc.")[1].toLowerCase(); + String exName = instanceName.split(".heat.")[1].toLowerCase(); + + JSONArray jArr = getVFInstances(resource, user, null); + + for (Object instanceObj : jArr) { + JSONObject instance = (JSONObject) JSONValue.parse(instanceObj.toString()); + String componentName = instance.get("componentName").toString().toLowerCase(); + String name = instance.get("name").toString().toLowerCase(); + + if (componentName.contains(exCompName) || name.toLowerCase().equals(exName)) { + List<String> actualDeploymentArtifacts = getActualVfcInstanceArtifactsFromJson(DEPLOYMENT_ARTIFACTS, instance); + List<String> actualInformationalArtifacts = getActualVfcInstanceArtifactsFromJson(ARTIFACTS, instance); + + if (actualDeploymentArtifacts != null) { + for (int i = 0; i < actualDeploymentArtifacts.size(); i++) { + String actualArtifactsString = actualDeploymentArtifacts.get(i); + JSONObject acArtifact = ((JSONObject) JSONValue.parse(actualArtifactsString)); + + if (acArtifact.containsKey("artifactName")) { + String acArtifactType = acArtifact.get("artifactName").toString(); + String acArtifactFileName = acArtifact.get("artifactType").toString(); + String acArtifactUUID = acArtifact.get("artifactUUID").toString(); + String acArtifactVersion = acArtifact.get("artifactVersion").toString(); + + vfcArtifactList.add(new VFCArtifact(acArtifactType, acArtifactFileName, acArtifactUUID, acArtifactVersion)); + } + } + } + if (actualInformationalArtifacts != null) { + for (int i = 0; i < actualInformationalArtifacts.size(); i++) { + String actualArtifactsString = actualInformationalArtifacts.get(i); + JSONObject acArtifact = ((JSONObject) JSONValue.parse(actualArtifactsString)); + + if (acArtifact.containsKey("artifactName")) { + String acArtifactType = acArtifact.get("artifactName").toString(); + String acArtifactFileName = acArtifact.get("artifactType").toString(); + String acArtifactUUID = acArtifact.get("artifactUUID").toString(); + String acArtifactVersion = acArtifact.get("artifactVersion").toString(); + vfcArtifactList.add(new VFCArtifact(acArtifactType, acArtifactFileName, acArtifactUUID, acArtifactVersion)); + } + + + } + } + } + } + } + +} + + + diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VFCverificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VFCverificator.java new file mode 100644 index 0000000000..e12e079bb9 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VFCverificator.java @@ -0,0 +1,40 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; + +import static org.testng.AssertJUnit.assertFalse; + + +public class VFCverificator { + + private VFCverificator() { + } + + public static void verifyVFCUpdatedInUI(ResourceReqDetails vf) { + assertFalse(vf.getName().equals(ResourceGeneralPage.getNameText())); + assertFalse(vf.getDescription().equals(ResourceGeneralPage.getDescriptionText())); + assertFalse(vf.getVendorName().equals(ResourceGeneralPage.getVendorNameText())); + assertFalse(vf.getVendorRelease().equals(ResourceGeneralPage.getVendorReleaseText())); + } +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VfModuleVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VfModuleVerificator.java new file mode 100644 index 0000000000..4d4c98e45e --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VfModuleVerificator.java @@ -0,0 +1,155 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + +import com.aventstack.extentreports.Status; +import org.onap.sdc.backend.ci.tests.datatypes.TypeHeatMetaDefinition; +import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition; +import org.openecomp.sdc.be.model.ComponentInstance; +import org.openecomp.sdc.be.model.GroupInstance; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.Service; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaGroupsTopologyTemplateDefinition; +import org.onap.sdc.backend.ci.tests.tosca.datatypes.ToscaServiceGroupsMetadataDefinition; + +import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertTrue; + +public class VfModuleVerificator { + + private VfModuleVerificator() { + } + + private static final List<String> PROPERTY_TYPES = DeploymentViewVerificator.getCurrentPropertiesWithoutIsBase(); //{"vf_module_label", "min_vf_module_instances", "max_vf_module_instances", "initial_count"}; + private static final String VF_MODULE_TYPE = "org.openecomp.groups.VfModule"; + + /** + * compare number of groups from HEAT.meta file vs TOSCA yaml groups generated by ASDC + * + * @param listTypeHeatMetaDefinition - java object created from HEAT.meta file + * @param toscaDefinition - java object created from TOSCA yaml + */ + public static void compareNumberOfVfModules(List<TypeHeatMetaDefinition> listTypeHeatMetaDefinition, ToscaDefinition toscaDefinition) { + + int heatMetaGroupCount = 0; + int toscaDefinitionGroupCount = 0; + for (TypeHeatMetaDefinition typeHeatMetaDefinition : listTypeHeatMetaDefinition) { + if (!typeHeatMetaDefinition.getTypeName().equals("artifacts")) { + heatMetaGroupCount = typeHeatMetaDefinition.getGroupHeatMetaDefinition().size(); + } + } + toscaDefinitionGroupCount = toscaDefinition.getTopology_template().getGroups().size(); + assertEquals("Expected num of groups in HEAT.meta file is " + heatMetaGroupCount + ", but was in TOSCA yaml file " + toscaDefinitionGroupCount, heatMetaGroupCount, toscaDefinitionGroupCount); + } + + /** + * check group structure and "metadata" parameters vs data on the service object + * + * @param toscaDefinition + */ + public static void verifyGroupMetadata(ToscaDefinition toscaDefinition, Service service) { + + Map<String, ToscaGroupsTopologyTemplateDefinition> groups = toscaDefinition.getTopology_template().getGroups(); + for (Map.Entry<String, ToscaGroupsTopologyTemplateDefinition> groupTopologyTemplateDefinition : groups.entrySet()) { + String key = groupTopologyTemplateDefinition.getKey(); + GroupInstance groupInstanceObject = getGroupInstanceByKey(key, service); + ToscaServiceGroupsMetadataDefinition metadata = groupTopologyTemplateDefinition.getValue(); + assertNotNull("groupInstanceObject is null", groupInstanceObject); + assertTrue("expected vfModuleModelName " + groupInstanceObject.getGroupName() + ", actual " + metadata.getVfModuleModelName(), groupInstanceObject.getGroupName().equals(metadata.getVfModuleModelName())); + assertTrue("expected vfModuleModelInvariantUUID " + groupInstanceObject.getInvariantUUID() + ", actual " + metadata.getVfModuleModelInvariantUUID(), groupInstanceObject.getInvariantUUID().equals(metadata.getVfModuleModelInvariantUUID())); + assertTrue("expected vfModuleModelCustomizationUUID " + groupInstanceObject.getCustomizationUUID() + ", actual " + metadata.getVfModuleModelCustomizationUUID(), groupInstanceObject.getCustomizationUUID().equals(metadata.getVfModuleModelCustomizationUUID())); + assertTrue("expected vfModuleModelUUID " + groupInstanceObject.getGroupUUID() + ", actual " + metadata.getVfModuleModelUUID(), groupInstanceObject.getGroupUUID().equals(metadata.getVfModuleModelUUID())); + assertTrue("expected vfModuleModelVersion " + groupInstanceObject.getVersion() + ", actual " + metadata.getVfModuleModelVersion(), groupInstanceObject.getVersion().equals(metadata.getVfModuleModelVersion())); + } + } + + + /** + * @param key + * @param service + * @return + */ + public static GroupInstance getGroupInstanceByKey(String key, Service service) { + for (ComponentInstance componentInstance : service.getComponentInstances()) { + for (GroupInstance groupInstance : componentInstance.getGroupInstances()) { + if (key.equals(groupInstance.getName())) { + return groupInstance; + } + } + } + return null; + } + + public static void validateSpecificModulePropertiesFromRequest(Resource resource) { + List<List<PropertyDataDefinition>> allProperties = resource.getGroups().stream(). + filter(e -> e.getType().equals(VF_MODULE_TYPE)). + map(e -> e.getProperties()). + collect(Collectors.toList()); + for (String propertyType : PROPERTY_TYPES) { + int numberOfTypes = getPropertyType(allProperties, propertyType).size(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating VF property %s exist, Expected: %s, Actual: %s ", propertyType, allProperties.size(), numberOfTypes)); + assertTrue(numberOfTypes == allProperties.size()); + } + } + + public static List<PropertyDataDefinition> getPropertyType(List<List<PropertyDataDefinition>> allProperties, String propertyType) { + return allProperties.stream(). + flatMap(List::stream). + filter(e -> e.getName().equals(propertyType)). + collect(Collectors.toList()); + } + + public static void validateSpecificModulePropertiesFromFile(ToscaDefinition toscaDefinition) { + List<ToscaGroupsTopologyTemplateDefinition> vfModules = toscaDefinition. + getTopology_template().getGroups().values().stream(). + filter(e -> e.getType().equals(VF_MODULE_TYPE)). + collect(Collectors.toList()); + for (String propertyType : PROPERTY_TYPES) { + int numberOfTypes = (int) vfModules.stream(). + // Get all declared fields from class ToscaGroupPropertyDefinition, collect them to List and check that current property exist and declared class + filter(e -> Arrays.asList(e.getProperties().getClass().getDeclaredFields()).stream(). + map(p -> p.getName()). + collect(Collectors.toList()). + contains(propertyType) + ). + collect(Collectors.toList()). + size(); + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating VF property %s exist, Expected: %s, Actual: %s ", propertyType, vfModules.size(), numberOfTypes)); + assertTrue(numberOfTypes == vfModules.size()); + } + } + + public static String getTemplateFilenname(String pathToCsar) { + File csarFile = new File(pathToCsar); + String templateFileName = csarFile.getName().replaceAll("-csar.csar", "-template.yml"); + return templateFileName; + } + +} diff --git a/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VfVerificator.java b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VfVerificator.java new file mode 100644 index 0000000000..fe853cd1d1 --- /dev/null +++ b/integration-tests/src/test/java/org/onap/sdc/frontend/ci/tests/verificator/VfVerificator.java @@ -0,0 +1,284 @@ +/*- + * ============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.onap.sdc.frontend.ci.tests.verificator; + + +import com.aventstack.extentreports.Status; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.http.HttpStatus; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; +import org.onap.sdc.backend.ci.tests.datatypes.ResourceReqDetails; +import org.onap.sdc.backend.ci.tests.datatypes.VendorSoftwareProductObject; +import org.onap.sdc.backend.ci.tests.datatypes.enums.PropertyTypeEnum; +import org.onap.sdc.backend.ci.tests.datatypes.http.RestResponse; +import org.onap.sdc.backend.ci.tests.utils.rest.ResponseParser; +import org.openecomp.sdc.be.model.LifecycleStateEnum; +import org.openecomp.sdc.be.model.Resource; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.model.category.CategoryDefinition; +import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum; +import org.onap.sdc.frontend.ci.tests.datatypes.LifeCycleStateEnum; +import org.onap.sdc.frontend.ci.tests.execute.setup.ExtentTestActions; +import org.onap.sdc.frontend.ci.tests.execute.setup.SetupCDTest; +import org.onap.sdc.frontend.ci.tests.pages.ResourceGeneralPage; +import org.onap.sdc.frontend.ci.tests.utilities.FileHandling; +import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.ResourceUIUtils; +import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils; +import org.openqa.selenium.By; +import org.openqa.selenium.WebElement; +import org.testng.Assert; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +public final class VfVerificator { + + private VfVerificator() { + } + + public static void verifyNumOfComponentInstances(ResourceReqDetails createResourceInUI, int numOfVFC, User user) { + ServiceVerificator.verifyNumOfComponentInstances(createResourceInUI, createResourceInUI.getVersion(), numOfVFC, user); + } + + public static void verifyRILocationChanged(ResourceReqDetails createResourceInUI, + ImmutablePair<String, String> prevRIPos, User user) { + + ImmutablePair<String, String> currRIPos = ResourceUIUtils.getFirstRIPos(createResourceInUI, user); + assertTrue(!prevRIPos.left.equals(currRIPos.left) || !prevRIPos.right.equals(currRIPos.right)); + } + + public static void verifyLinkCreated(ResourceReqDetails createResourceInUI, User user, int expectedRelationsSize) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying that a link was created on canvas")); + String responseAfterDrag = RestCDUtils.getResource(createResourceInUI, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + assertTrue(((JSONArray) jsonResource.get("componentInstancesRelations")).size() == expectedRelationsSize); + ExtentTestActions.log(Status.INFO, "The link was verified."); + + } + + public static void verifyVFMetadataInUI(ResourceReqDetails vf) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying fields on General screen through UI ...")); + assertTrue(vf.getName().equals(ResourceGeneralPage.getNameText())); + assertTrue(vf.getDescription().equals(ResourceGeneralPage.getDescriptionText())); + assertTrue(vf.getCategories().get(0).getSubcategories().get(0).getName().equals(GeneralUIUtils.getSelectedElementFromDropDown(ResourceGeneralPage.getCategoryDataTestsIdAttribute()).getText())); + assertTrue(vf.getVendorName().equals(ResourceGeneralPage.getVendorNameText())); + assertTrue(vf.getVendorRelease().equals(ResourceGeneralPage.getVendorReleaseText())); + assertTrue(vf.getContactId().equals(ResourceGeneralPage.getContactIdText())); + List<WebElement> tagsList = ResourceGeneralPage.getElementsFromTagsTable(); + assertTrue(vf.getTags().size() == tagsList.size()); + for (int i = 0; i < vf.getTags().size(); i++) { + assertTrue(vf.getTags().contains(tagsList.get(i).getText())); + } + assertTrue(vf.getContactId().equals(ResourceGeneralPage.getContactIdText())); + } + + public static void verifyVFUpdated(ResourceReqDetails vf, User user) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying fields on General screen through Backend ...")); + String response = RestCDUtils.getResource(vf, user).getResponse(); + Resource resource = ResponseParser.convertResourceResponseToJavaObject(response); + assertTrue(vf.getName().equals(resource.getName())); + assertTrue(vf.getDescription().equals(resource.getDescription())); + assertTrue(vf.getVendorName().equals(resource.getVendorName())); + assertTrue(vf.getVendorRelease().equals(resource.getVendorRelease())); + assertTrue(vf.getContactId().equals(resource.getContactId())); + + assertTrue(vf.getCategories().size() == (resource.getCategories().size())); + for (int i = 0; i < vf.getCategories().size(); i++) { + CategoryDefinition expectedCategoryDefinition = vf.getCategories().get(i); + CategoryDefinition actualCategoryDefinition = resource.getCategories().get(i); + assertTrue(expectedCategoryDefinition.getName().equals(actualCategoryDefinition.getName())); + assertTrue(expectedCategoryDefinition.getSubcategories().get(i).getName().equals(actualCategoryDefinition.getSubcategories().get(i).getName())); + } + + assertTrue(vf.getTags().size() == (resource.getTags().size())); + for (int i = 0; i < vf.getTags().size(); i++) { + List<String> expectedTags = vf.getTags(); + List<String> actualTags = resource.getTags(); + + assertTrue(actualTags.contains(expectedTags.get(i))); + + } + } + + public static void verifyVFLifecycle(ResourceReqDetails vf, User user, LifecycleStateEnum expectedLifecycleState) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verfiying that object %s state is %s", vf.getName(), expectedLifecycleState)); + String responseAfterDrag = RestCDUtils.getResource(vf, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + String actualLifecycleState = jsonResource.get("lifecycleState").toString(); + assertTrue(expectedLifecycleState.name().equals(actualLifecycleState), "actual: " + actualLifecycleState + "-- expected: " + expectedLifecycleState); + } + + public static void verifyVfLifecycleInUI(LifeCycleStateEnum lifecycleState) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verfiying that object state is %s", lifecycleState.getValue())); + GeneralUIUtils.ultimateWait(); + assertTrue(ResourceGeneralPage.getLifeCycleState().equals(lifecycleState.getValue())); + } + + public static void verifyVersionUI(String expected) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verifying that version is %s", expected)); + String actualVersion = GeneralUIUtils.getSelectedElementFromDropDown(DataTestIdEnum. + GeneralElementsEnum.VERSION_HEADER.getValue()).getText().replace("V", ""); + assertTrue(actualVersion.equals(expected), String.format("Expected version: %s, Actual version: %s", expected, actualVersion)); + } + + public static void verifyInstanceVersion(ResourceReqDetails vf, User user, String instanceName, String instanceVersion) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Verfiying that instance %s version is %s", instanceName, instanceVersion)); + String responseAfterDrag = RestCDUtils.getResource(vf, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + JSONArray jsonArrayResource = (JSONArray) jsonResource.get("componentInstances"); + for (int i = 0; i < jsonArrayResource.size(); i++) { + Object object = jsonArrayResource.get(i); + try { + JSONObject jRes = (JSONObject) JSONValue.parse(object.toString()); + String componentName = jRes.get("componentName").toString(); + if (componentName.equals(instanceName)) { + String componentVersion = jRes.get("componentVersion").toString(); + assertTrue(componentVersion.equals(instanceVersion)); + } + } catch (Exception e) { + System.out.println("Can't test object in componentInstances array"); + Assert.fail("Can't test object in componentInstances array"); + } + } + } + + public static void verifyVfDeleted(ResourceReqDetails vf, User user) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating resource %s was deleted", vf.getName())); + RestResponse response = RestCDUtils.getResource(vf, user); + assertTrue(response.getErrorCode().intValue() == HttpStatus.SC_NOT_FOUND); + } + + public static void verifyPropertiesInUI(List<PropertyTypeEnum> propertyList) { + + for (PropertyTypeEnum prop : propertyList) { + String propName = prop.getName(); + + String actualName = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_NAME.getValue() + propName).getText(); + String actualType = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_TYPE.getValue() + propName).getText(); + String actualDesciprtion = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.PROPERTY_DESCRIPTION.getValue() + propName).getText(); + + assertTrue(propName.equals(actualName), String.format("Property name is not correct. expected:%s ; actual %s", propName, actualName)); + assertTrue(prop.getType().equals(actualType), String.format("Property type is not correct. expected:%s ; actual %s", prop.getType(), actualType)); + assertTrue(prop.getDescription().equals(actualDesciprtion), String.format("Property description is not correct. expected:%s ; actual %s", prop.getDescription(), actualDesciprtion)); + + if (prop.getSchemaDefinition() != null) { + String actualSchema = GeneralUIUtils.getWebElementByTestID(DataTestIdEnum.PropertiesPageEnum.ENTRY_SCHEMA.getValue() + propName).getText(); + assertTrue(prop.getSchemaDefinition().equals(actualSchema), String.format("Property schema is not correct. expected:%s ; actual %s", prop.getSchemaDefinition(), actualSchema)); + } + } + } + + public static void verifyToscaArtifactsInfo(ResourceReqDetails vf, User user) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Validating Tosca Aritfact Info of resource %s", vf.getName())); + String responseAfterDrag = RestCDUtils.getResource(vf, user).getResponse(); + JSONObject jsonResource = (JSONObject) JSONValue.parse(responseAfterDrag); + JSONObject toscaArtifacts = (JSONObject) jsonResource.get("toscaArtifacts"); + + assertEquals(2, toscaArtifacts.size()); + for (Object artifactObj : toscaArtifacts.keySet()) { + JSONObject artifact = (JSONObject) JSONValue.parse(toscaArtifacts.get(artifactObj).toString()); + assertFalse(artifact.get("artifactUUID").toString().isEmpty(), "artifactUUID field is empty"); + assertFalse(artifact.get("artifactChecksum").toString().isEmpty(), "artifactChecksum filed is empty"); + assertFalse(artifact.get("payloadUpdateDate").toString().isEmpty(), "payloadUpdateDate field is empty"); + assertFalse(artifact.get("artifactVersion").toString().equals("0"), "artifactVersion field is 0"); + } + } + + public static void verifyVfInputs(String instanceName, Map<String, String> instancePropertiesMapFromJson, List<WebElement> propertyRowsFromTable) { + + for (int i = 0; i < propertyRowsFromTable.size(); i++) { + WebElement row = propertyRowsFromTable.get(i); + String propertyNameFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "propertyName']")).getText(); + String propertyTypeFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "propertyType']")).getText(); + String instanceNameFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "instanceName']")).getText(); + String propertySchemaFromTable = row.findElement(By.xpath(".//*[@data-tests-id='" + "propertySchema']")).getText(); + + assertTrue(instancePropertiesMapFromJson.containsKey(propertyNameFromTable), "No property named : " + propertyNameFromTable + "for instance " + instanceName); + String expectedType = instancePropertiesMapFromJson.get(propertyNameFromTable); + assertTrue(expectedType.equals(propertyTypeFromTable.toLowerCase()), propertyNameFromTable + "type is incorrect"); + assertTrue(instanceName.equals(instanceNameFromTable), "Instance name of property named " + propertyNameFromTable + "is incorrect"); + } + } + + public static void verifyOnboardedVnfMetadata(String vspName, VendorSoftwareProductObject vspMetadata) { + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying metadata"); + + assertTrue(vspName.equals(ResourceGeneralPage.getNameText()), "VSP name is not valid."); + List<WebElement> tagsList = ResourceGeneralPage.getElementsFromTagsTable(); + assertTrue(tagsList.size() == 1, "VSP tags size is not equal to 1."); + assertTrue(vspName.equals(tagsList.get(0).getText()), "VSP tag is not its name."); + + verifyMetadataIndifferentToFlow(vspMetadata); + } + + public static void verifyOnboardedVnfMetadataAfterUpdateVNF(String vspName, VendorSoftwareProductObject vspMetadata) { + SetupCDTest.getExtendTest().log(Status.INFO, "Verifying metadata after update VNF"); + + // VF name should be updated only only if VF not certified + if (Double.parseDouble(ResourceGeneralPage.getVersionUI()) < 1.0) { + assertTrue(vspName.equals(ResourceGeneralPage.getNameText()), "VSP name is not valid."); + List<WebElement> tagsList = ResourceGeneralPage.getElementsFromTagsTable(); + assertTrue(tagsList.size() == 1, "VSP tags size is not equal to 1."); + assertTrue(vspName.equals(tagsList.get(0).getText()), "VSP tag is not its name."); + } + + verifyMetadataIndifferentToFlow(vspMetadata); + } + + public static void verifyMetadataIndifferentToFlow(VendorSoftwareProductObject vspMetadata) { + assertTrue(vspMetadata.getDescription().equals(ResourceGeneralPage.getDescriptionText()), "VSP description is not valid."); + + String[] splitedSubCategorey = vspMetadata.getSubCategory().split("\\."); + String expectedSubCategory = splitedSubCategorey[splitedSubCategorey.length - 1]; + String actualSubCategory = GeneralUIUtils.getSelectedElementFromDropDown(ResourceGeneralPage.getCategoryDataTestsIdAttribute()).getText().trim().toLowerCase(); + + assertTrue(expectedSubCategory.equals(actualSubCategory), "VSP category is not valid."); + assertTrue(vspMetadata.getVendorName().equals(ResourceGeneralPage.getVendorNameText()), "VSP vendor name is not valid."); + assertTrue("1.0".equals(ResourceGeneralPage.getVendorReleaseText()), "VSP version is not valid."); + assertTrue(vspMetadata.getAttContact().equals(ResourceGeneralPage.getContactIdText()), "VSP attContact is not valid."); + } + + public static void verifyIsElementDisabled(String elementLocator, String elementName) { + SetupCDTest.getExtendTest().log(Status.INFO, String.format("Checking if %s is disabled", elementName)); + assertTrue(GeneralUIUtils.isElementReadOnly(elementLocator)); + } + + public static void verifyFilesChecksum(File actual, File expected) { + try { + String actualMd5OfFile = FileHandling.getMD5OfFile(actual); + String expectedMd5OfFile = FileHandling.getMD5OfFile(expected); + Assert.assertEquals(expectedMd5OfFile, actualMd5OfFile, "File does not exist"); + } catch (IOException e) { + e.printStackTrace(); + } + + } + +} |