2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.ci.tests.execute.setup;
23 import ch.qos.logback.classic.Level;
24 import ch.qos.logback.classic.LoggerContext;
25 import com.aventstack.extentreports.ExtentTest;
26 import com.aventstack.extentreports.Status;
27 import net.lightbody.bmp.core.har.Har;
28 import org.json.simple.JSONObject;
29 import org.openecomp.sdc.be.model.User;
30 import org.openecomp.sdc.ci.tests.api.SomeInterface;
31 import org.openecomp.sdc.ci.tests.config.UserCredentialsFromFile;
32 import org.openecomp.sdc.ci.tests.datatypes.DataTestIdEnum;
33 import org.openecomp.sdc.ci.tests.datatypes.UserCredentials;
34 import org.openecomp.sdc.ci.tests.datatypes.enums.UserRoleEnum;
35 import org.openecomp.sdc.ci.tests.execute.sanity.OnboardingFlowsUI;
36 import org.openecomp.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml;
37 import org.openecomp.sdc.ci.tests.pages.HomePage;
38 import org.openecomp.sdc.ci.tests.run.StartTest;
39 import org.openecomp.sdc.ci.tests.utilities.FileHandling;
40 import org.openecomp.sdc.ci.tests.utilities.GeneralUIUtils;
41 import org.openecomp.sdc.ci.tests.utilities.RestCDUtils;
42 import org.openecomp.sdc.ci.tests.utils.rest.AutomationUtils;
43 import org.openqa.selenium.By;
44 import org.openqa.selenium.JavascriptExecutor;
45 import org.openqa.selenium.WebDriver;
46 import org.openqa.selenium.WebElement;
47 import org.openqa.selenium.support.ui.ExpectedConditions;
48 import org.openqa.selenium.support.ui.WebDriverWait;
49 import org.slf4j.LoggerFactory;
50 import org.testng.Assert;
51 import org.testng.ITestContext;
52 import org.testng.ITestResult;
53 import org.testng.annotations.*;
56 import java.io.FileWriter;
57 import java.io.IOException;
58 import java.util.Arrays;
59 import java.util.UUID;
61 public abstract class SetupCDTest extends DriverFactory {
63 // private static final String RE_RUN = "ReRun - ";
64 private static final String RE_RUN = "<html><font color=\"red\">ReRun - </font></html>";
65 private static final String WEB_SEAL_PASSWORD = "123123a";
66 protected static final String HEAT_FILE_YAML_NAME_PREFIX = "Heat-File";
67 protected static final String HEAT_FILE_YAML_NAME_SUFFIX = ".yaml";
69 public SetupCDTest() {
70 LoggerContext lc = (LoggerContext) LoggerFactory. getILoggerFactory();
71 lc.getLogger("org.apache").setLevel(Level.INFO);
74 /**************** CONSTANTS ****************/
75 private static final String CREDENTIALS_FILE = "credentials.yaml";
76 private static final String REPORT_FILE_NAME = "SDC_UI_Extent_Report.html";
77 protected static final String REPORT_FOLDER = "." + File.separator + "ExtentReport" + File.separator;
78 protected static final String SCREENSHOT_FOLDER = REPORT_FOLDER + "screenshots" + File.separator;
79 protected static final String HAR_FILES_FOLDER_NAME = "har_files";
80 protected static final String HAR_FILES_FOLDER = REPORT_FOLDER + HAR_FILES_FOLDER_NAME + File.separator;
83 private static final String SHORT_CSV_REPORT_FILE_NAME = "ShortReport.csv";
84 private static final int NUM_OF_ATTEMPTS_TO_REFTRESH = 2;
87 /**************** PRIVATES ****************/
88 private static String url;
89 private static boolean uiSimulator;
90 private static boolean localEnv = true;
91 private static OnboardCSVReport csvReport;
92 private final UserCredentialsFromFile credentialsIns = UserCredentialsFromFile.getInstance();
94 protected static ITestContext myContext;
97 /**************** METHODS ****************/
98 public static ExtentTest getExtendTest() {
99 SomeInterface testManager = new ExtentTestManager();
100 return testManager.getTest();
102 public static WindowTest getWindowTest(){
103 return WindowTestManager.getWindowMap();
106 public OnboardCSVReport getCsvReport() {
110 public static String getReportFolder() {
111 return REPORT_FOLDER;
114 public static String getScreenshotFolder() {
115 return SCREENSHOT_FOLDER;
118 public static String getHarFilesFolder() {
119 return HAR_FILES_FOLDER;
123 protected abstract UserRoleEnum getRole();
125 /**************** BEFORE ****************/
127 @BeforeSuite(alwaysRun = true)
128 public void setupBeforeSuite(ITestContext context) throws Exception {
129 RestCDUtils.deleteOnDemand();
131 setErrorConfigurationFile();
133 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
134 csvReport = new OnboardCSVReport(getReportFolder(), SHORT_CSV_REPORT_FILE_NAME);
137 private static void setErrorConfigurationFile() {
138 if (!System.getProperty("os.name").contains("Windows")){
139 String errorConfigurationFilename = getConfig().getErrorConfigurationFile();
140 errorConfigurationFilename = errorConfigurationFilename.substring(errorConfigurationFilename.lastIndexOf("/") + 1, errorConfigurationFilename.length());
141 getConfig().setErrorConfigurationFile(FileHandling.getBasePath() + File.separator + "conf" + File.separator + errorConfigurationFilename);
142 if (new File(getConfig().getErrorConfigurationFile()).exists()){
143 System.out.println("Found error-configuration.yaml in : " + getConfig().getErrorConfigurationFile());
148 @BeforeMethod(alwaysRun = true )
149 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
151 boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
152 String className = method.getDeclaringClass().getName();
153 if (emptyDataProvider && !className.contains("ToscaValidationTest") ) {
154 System.out.println("ExtentReport instance started from BeforeMethod...");
155 String suiteName = ExtentManager.getSuiteName(context);
156 if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
157 ExtentTestManager.startTest(RE_RUN + method.getName());
159 ExtentTestManager.startTest(method.getName());
162 ExtentTestManager.assignCategory(this.getClass());
163 setBrowserBeforeTest(getRole());
165 System.out.println("ExtentReport instance started from Test...");
168 getConfig().setWindowsDownloadDirectory(getWindowTest().getDownloadDirectory());
170 if (getConfig().getCaptureTraffic()){
172 MobProxy.getPoxyServer().newHar(method.getName() + ".har");
173 } catch (Throwable e) {
179 /**************** AFTER ****************/
180 @AfterMethod(alwaysRun = true)
181 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
184 ReportAfterTestManager.report(result, context);
185 GeneralUIUtils.closeErrorMessage();
189 if (getConfig().getCaptureTraffic()){
190 addTrafficFileToReport(result);
193 if (result.getInstanceName().equals(OnboardingFlowsUI.class.getName()) && result.getStatus() == ITestResult.FAILURE){
194 System.out.println("Onboarding test failed, closign browser....");
195 getExtendTest().log(Status.INFO, "Onboarding test failed, closing browser....");
198 else if (!getUser().getRole().toLowerCase().equals(UserRoleEnum.ADMIN.name().toLowerCase())){
199 boolean navigateToHomePageSuccess = HomePage.navigateToHomePage();
200 if (!navigateToHomePageSuccess){
201 System.out.println("Navigating to homepage failed, reopening driver....");
202 getExtendTest().log(Status.INFO, "Navigating to homepage failed, reopening driver....");
207 } catch (Exception e) {
209 getExtendTest().log(Status.ERROR, "Exception:"+ e.toString());
214 ExtentTestManager.endTest();
215 String suiteName = ExtentManager.getSuiteName(context);
216 // write result to csv file
217 if((!suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) && (result.getStatus() == ITestResult.SKIP)) {
218 addResultToCSV(result, context);
220 if(suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue()) && !(result.getStatus() == ITestResult.SUCCESS)) {
221 addResultToCSV(result, context);
223 // ExtentManager.closeReporter();
224 FileHandling.cleanCurrentDownloadDir();
228 public void addResultToCSV(ITestResult result, ITestContext context) {
229 // String suiteName = ExtentManager.getSuiteName(context);
230 ExtentTest test = getExtendTest();
231 com.aventstack.extentreports.model.Test model = test.getModel();
232 String name = model.getName();
233 String status = model.getStatus().toString();
234 // if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue()) && !(result.getStatus() == ITestResult.SUCCESS)) {
235 getCsvReport().writeRow(result.getInstanceName(), name.replace(RE_RUN,""), status);
239 public void generateReport4Jenkins(ITestContext context) {
240 String suiteName = ExtentManager.getSuiteName(context);
241 // String outputDirectory = context.getOutputDirectory();
242 JSONObject obj = new JSONObject();
243 String success = Integer.toString(context.getPassedTests().size());
244 String failed = Integer.toString(context.getFailedTests().size());
245 String total = Integer.toString(context.getFailedTests().size()+context.getPassedTests().size());
246 obj.put("projectName", "SDC-ONAP-UI-Automation-"+suiteName);
247 obj.put("projectVersion", AutomationUtils.getOSVersion());
248 obj.put("platform", "Linux");
249 obj.put("total", total);
250 obj.put("success", success);
251 obj.put("failed", failed);
253 try (FileWriter file = new FileWriter(getReportFolder() + "jenkinsResults.json")) {
255 file.write(obj.toJSONString());
258 } catch (IOException e) {
262 System.out.print(obj);
268 @Parameters({ "eraseAfterTests" })
269 @AfterSuite(alwaysRun = true)
270 public void afterSuite2(@Optional("true") String eraseAfterTestsReadValue) throws Exception {
271 // public void afterSuite() throws Exception {
273 csvReport.closeFile();
274 generateReport4Jenkins(myContext);
276 if (Boolean.parseBoolean(eraseAfterTestsReadValue)){
277 RestCDUtils.deleteOnDemand();
279 System.out.println("Resources will not be deleted according to suite configuration ...");
282 if (getConfig().getUseBrowserMobProxy()){
283 MobProxy.getPoxyServer().stop();
287 protected static String setUrl() {
288 url = getConfig().getUrl();
289 uiSimulator = getConfig().isUiSimulator();
291 String message = "no URL found";
292 System.out.println(message);
293 Assert.fail(message);
294 } else if (!url.contains("localhost") && !url.contains("192.168.33.10") && !url.contains("127.0.0.1") && !url.contains("192.168.50.5") && !uiSimulator==true) {
302 public static void navigateToUrl(String url) throws Exception {
304 System.out.println("Deleting cookies...");
307 System.out.println("Navigating to URL : " + url);
308 getDriver().navigate().to(url);
309 GeneralUIUtils.waitForLoader();
311 System.out.println("Zooming out...");
312 GeneralUIUtils.windowZoomOutUltimate();
315 catch (Exception e) {
316 String msg = "Browser is unreachable";
317 System.out.println(msg);
318 getExtendTest().log(Status.ERROR, msg);
322 private static void deleteCookies() throws Exception {
323 getDriver().manage().deleteAllCookies();
327 final int max_attempts = 3;
329 while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts){
330 getExtendTest().log(Status.INFO, "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts");
331 String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });";
332 ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS);
335 if (attempts == max_attempts){
336 String msg = "Did not delete cookies, can't login as user " + WindowTestManager.getWindowMap().getUser().getRole();
337 System.out.println(msg);
338 getExtendTest().log(Status.ERROR, msg);
344 protected void loginToSystem(UserRoleEnum role) throws Exception {
345 UserCredentials credentials = new UserCredentials(role.getUserId(), role.getPassword(), role.getFirstName(), role.getLastName(), role.name());
347 loginToSimulator(role);
350 sendUserAndPasswordKeys(credentials);
351 WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), 30);
352 submitButton.click();
353 WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), 30);
354 Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed.");
357 GeneralUIUtils.ultimateWait();
358 getWindowTest().setUser(credentials);
361 private void goToHomePage(UserRoleEnum role) throws Exception {
363 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() == 0 ? NUM_OF_ATTEMPTS_TO_REFTRESH : getWindowTest().getRefreshAttempts());
364 if (!role.equals(UserRoleEnum.ADMIN)) {
366 WebElement closeButton = GeneralUIUtils.getClickableButtonBy(By.className("sdc-welcome-close"), 10);
367 if (closeButton != null){
371 if (!GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue()))
373 restartBrowser(role);
377 catch (Exception e) {
378 restartBrowser(role);
381 private void restartBrowser(UserRoleEnum role) throws Exception {
382 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() - 1);
383 if (getWindowTest().getRefreshAttempts() <= 0) {
384 System.out.println("ERR : Something is wrong with browser!");
385 Assert.fail("ERR : Something is wrong with browser!");
387 System.out.println("Trying again...");
388 getExtendTest().log(Status.INFO, "Trying again...");
389 getExtendTest().log(Status.INFO, String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts() ));
390 System.out.println(String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts() ));
392 reloginWithNewRole(role);
395 public void loginToSimulator(UserRoleEnum role){
396 WebDriver driver = GeneralUIUtils.getDriver();
397 WebDriverWait wait = new WebDriverWait(driver, 30);
399 wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']"))));
401 WebElement userIdTextbox = GeneralUIUtils.getWebElementBy(By.name("userId"));
402 userIdTextbox.sendKeys(role.getUserId());
403 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
404 passwordTextbox.sendKeys(WEB_SEAL_PASSWORD);
406 wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click();
409 private void sendUserAndPasswordKeys(UserCredentials userId) {
410 System.out.println("Login as user : " + userId.getUserId());
411 WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid"));
412 userNameTextbox.sendKeys(userId.getUserId());
413 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
414 passwordTextbox.sendKeys(userId.getPassword());
417 public void loginWithUser(UserRoleEnum role) {
419 getExtendTest().log(Status.INFO, String.format("Login as user %s", role.name().toUpperCase()));
422 } catch (Exception e) {
423 throw new RuntimeException(e);
426 getWindowTest().setPreviousRole(getWindowTest().getUser().getRole());
430 private void setUser(UserRoleEnum role) {
431 User user = new User();
432 user.setUserId(role.getUserId());
433 user.setFirstName(role.getFirstName());
434 user.setRole(role.name());
435 user.setLastName(role.getLastName());
437 getWindowTest().setUser(user);
440 public User getUser() {
441 return getWindowTest().getUser();
444 private void setBrowserBeforeTest(UserRoleEnum role) {
445 System.out.println(String.format("Setup before test as %s.", role.toString().toUpperCase() ));
447 System.out.println("Previous role is : " + getWindowTest().getPreviousRole() + " ; Current role is : " + role.name());
448 if (!getWindowTest().getPreviousRole().toLowerCase().equals(role.name().toLowerCase())){
449 System.out.println("Roles are different, navigate and login");
450 navigateAndLogin(role);
452 } catch (Exception e) {
457 public void navigateAndLogin(UserRoleEnum role) throws Exception {
458 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() != 0 ? getWindowTest().getRefreshAttempts() : 0);
462 GeneralUIUtils.ultimateWait();
465 public User getUser(UserRoleEnum role) {
466 User user = new User();
467 user.setUserId(role.getUserId());
468 user.setFirstName(role.getFirstName());
469 user.setLastName(role.getLastName());
470 user.setRole(role.name());
474 protected void reloginWithNewRole(UserRoleEnum role) throws Exception {
475 System.out.println(String.format("Setup before relogin as %s", role.toString().toUpperCase()));
476 navigateAndLogin(role);
479 /*public static void setLocalUrl(UserRoleEnum role) {
482 url = "http://localhost:8181/sdc1/proxy-admin1#/dashboard";
486 url = "http://localhost:8181/sdc1/proxy-designer1#/dashboard";
490 url = "http://localhost:8181/sdc1/proxy-governor1#/dashboard";
494 url = "http://localhost:8181/sdc1/proxy-ops1#/dashboard";
498 url = "http://localhost:8181/sdc1/proxy-tester1#/dashboard";
501 case PRODUCT_MANAGER1: {
502 url = "http://localhost:8181/sdc1/proxy-pm1#/dashboard";
505 case PRODUCT_MANAGER2: {
506 url = "http://localhost:8181/sdc1/proxy-pm2#/dashboard";
509 case PRODUCT_STRATEGIST1: {
510 url = "http://localhost:8181/sdc1/proxy-ps1#/dashboard";
513 case PRODUCT_STRATEGIST2: {
514 url = "http://localhost:8181/sdc1/proxy-ps2#/dashboard";
523 public void addTrafficFileToReport(ITestResult result) {
526 Har har = MobProxy.getPoxyServer().getHar();
527 String shortUUID = UUID.randomUUID().toString().split("-")[0];
528 File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har");
529 new File(getHarFilesFolder()).mkdirs();
531 har.writeTo(harFile);
533 String pathToFileFromReportDirectory = HAR_FILES_FOLDER_NAME + File.separator + harFile.getName();
534 ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory, "File with captured traffic");
535 } catch (IOException ioe) {
536 ioe.printStackTrace();
541 * * Start section of test in ExtentReport with DataProvider parameters,
542 * should be started from test method, see example in onboardVNFTest
544 public void setLog(String fromDataProvider) {
546 String suiteName = ExtentManager.getSuiteName(myContext);
547 if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
548 ExtentTestManager.startTest(RE_RUN +Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
550 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
555 getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
556 ExtentTestManager.assignCategory(this.getClass());
557 setBrowserBeforeTest(getRole());
562 /**************** MAIN ****************/
563 public static void main(String[] args) {
564 System.out.println("---------------------");
565 System.out.println("running test from CLI");
566 System.out.println("---------------------");
568 String attsdcFilePath = FileHandling.getBasePath() + File.separator + "conf" + File.separator + "attsdc.yaml";
569 System.setProperty("config.resource", attsdcFilePath);
570 System.out.println("attsdc.yaml file path is : " + attsdcFilePath);
572 String filepath = FileHandling.getBasePath() + File.separator + "Files" + File.separator;
573 System.setProperty("filePath", filepath);
574 System.out.println("filePath is : " + System.getProperty("filePath"));
576 Object[] testSuitsList = FileHandling.filterFileNamesFromFolder(FileHandling.getBasePath() + File.separator + "testSuites", ".xml");
577 if (testSuitsList != null) {
578 System.out.println(String.format("Found %s testSuite(s)", testSuitsList.length));
579 args = Arrays.copyOf(testSuitsList, testSuitsList.length, String[].class);
580 StartTest.main(args);