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.onap.sdc.frontend.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;
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.util.Arrays;
32 import java.util.UUID;
34 import net.lightbody.bmp.core.har.Har;
35 import org.json.simple.JSONObject;
36 import org.onap.sdc.backend.ci.tests.config.UserCredentialsFromFile;
37 import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum;
38 import org.onap.sdc.frontend.ci.tests.datatypes.UserCredentials;
39 import org.onap.sdc.frontend.ci.tests.execute.sanity.OnboardingFlowsUi;
40 import org.onap.sdc.frontend.ci.tests.pages.HomePage;
41 import org.onap.sdc.frontend.ci.tests.utilities.FileHandling;
42 import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils;
43 import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils;
44 import org.onap.sdc.backend.ci.tests.utils.rest.AutomationUtils;
45 import org.openecomp.sdc.be.model.User;
46 import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum;
47 import org.openqa.selenium.By;
48 import org.openqa.selenium.JavascriptExecutor;
49 import org.openqa.selenium.WebDriver;
50 import org.openqa.selenium.WebElement;
51 import org.openqa.selenium.support.ui.ExpectedConditions;
52 import org.openqa.selenium.support.ui.WebDriverWait;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.testng.Assert;
56 import org.testng.ITestContext;
57 import org.testng.ITestResult;
58 import org.testng.annotations.AfterMethod;
59 import org.testng.annotations.AfterSuite;
60 import org.testng.annotations.BeforeMethod;
61 import org.testng.annotations.BeforeSuite;
62 import org.testng.annotations.Optional;
63 import org.testng.annotations.Parameters;
64 import org.testng.annotations.Test;
66 public abstract class SetupCDTest extends DriverFactory {
68 private static final Logger LOGGER = LoggerFactory.getLogger(SetupCDTest.class);
70 private static final String RE_RUN = "<html><font color=\"red\">ReRun - </font></html>";
71 private static final String WEB_SEAL_PASSWORD = "123123a";
72 protected static final String HEAT_FILE_YAML_NAME_PREFIX = "Heat-File";
73 protected static final String HEAT_FILE_YAML_NAME_SUFFIX = ".yaml";
74 private static final int BASIC_SLEEP_DURATION = 1000;
76 /**************** CONSTANTS ****************/
77 private static final String CREDENTIALS_FILE = "credentials.yaml";
79 private static final String REPORT_FILE_NAME = "SDC_UI_Extent_Report.html";
80 private static final String REPORT_FOLDER = "target" + File.separator + "ExtentReport" + File.separator + "UI" + File.separator;
81 private static final String SCREENSHOT_FOLDER = REPORT_FOLDER + "screenshots" + File.separator;
82 private static final String HAR_FILES_FOLDER_NAME = "har_files";
83 private static final String HAR_FILES_FOLDER = REPORT_FOLDER + HAR_FILES_FOLDER_NAME + File.separator;
85 private static final String SHORT_CSV_REPORT_FILE_NAME = "ShortReport.csv";
87 private static final int NUM_OF_ATTEMPTS_TO_REFTRESH = 2;
89 /**************** PRIVATES ****************/
90 private static String url;
92 private static boolean uiSimulator;
93 private static boolean localEnv = true;
94 private static OnboardCSVReport csvReport;
95 private final UserCredentialsFromFile credentialsIns = UserCredentialsFromFile.getInstance();
96 private static ITestContext myContext;
98 public SetupCDTest() {
99 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
100 lc.getLogger("org.apache").setLevel(Level.INFO);
103 public static ExtentTest getExtendTest() {
104 return ExtentTestManager.getInstance().getTest();
107 public static WindowTest getWindowTest() {
108 return WindowTestManager.getWindowMap();
111 private OnboardCSVReport getCsvReport() {
115 public static String getReportFolder() {
116 return REPORT_FOLDER;
119 public static String getScreenshotFolder() {
120 return SCREENSHOT_FOLDER;
123 private static String getHarFilesFolder() {
124 return HAR_FILES_FOLDER;
128 protected abstract UserRoleEnum getRole();
130 /**************** BEFORE ****************/
132 @BeforeSuite(alwaysRun = true)
133 public void setupBeforeSuite(ITestContext context) throws Exception {
134 RestCDUtils.deleteOnDemand();
137 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
138 csvReport = new OnboardCSVReport(getReportFolder(), SHORT_CSV_REPORT_FILE_NAME);
141 @BeforeMethod(alwaysRun = true)
142 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
144 boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
145 String className = method.getDeclaringClass().getName();
146 if (emptyDataProvider && !className.contains("ToscaValidationTest")) {
147 System.out.println("ExtentReport instance started from BeforeMethod...");
148 String suiteName = ExtentManager.getSuiteName(context);
149 if (suiteName.equals(ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
150 ExtentTestManager.getInstance().startTest(RE_RUN + method.getName());
152 ExtentTestManager.getInstance().startTest(method.getName());
155 ExtentTestManager.getInstance().assignCategory(this.getClass());
156 setBrowserBeforeTest(getRole());
158 System.out.println("ExtentReport instance started from Test...");
161 if (getConfig().getCaptureTraffic()) {
163 MobProxy.getPoxyServer().newHar(method.getName() + ".har");
164 } catch (Throwable e) {
170 /**************** AFTER ****************/
171 @AfterMethod(alwaysRun = true)
172 public void quitAfterTest(final ITestResult result, final ITestContext context) throws Exception {
174 ReportAfterTestManager.report(result, context);
175 GeneralUIUtils.closeErrorMessage();
178 if (getConfig().getCaptureTraffic()) {
179 addTrafficFileToReport(result);
182 if (result.getInstanceName().equals(OnboardingFlowsUi.class.getName()) && result.getStatus() == ITestResult.FAILURE) {
183 final String msg = "Onboarding test failed, closing browser";
185 getExtendTest().log(Status.INFO, msg);
187 } else if (!getUser().getRole().toLowerCase().equals(UserRoleEnum.ADMIN.name().toLowerCase())) {
188 boolean navigateToHomePageSuccess = HomePage.navigateToHomePage();
189 if (!navigateToHomePageSuccess) {
190 final String msg = "Navigating to homepage failed, reopening driver";
192 getExtendTest().log(Status.INFO, msg);
197 } catch (final Exception e) {
198 LOGGER.error("An unexpected error has occurred", e);
199 getExtendTest().log(Status.ERROR, "Exception:" + e.toString());
203 ExtentTestManager.getInstance().endTest();
204 final String suiteName = ExtentManager.getSuiteName(context);
205 // write result to csv file
206 if ((!ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName)) && (result.getStatus() == ITestResult.SKIP)) {
207 addResultToCSV(result, context);
209 if (ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName) && !(result.getStatus() == ITestResult.SUCCESS)) {
210 addResultToCSV(result, context);
212 FileHandling.cleanCurrentDownloadDir();
217 private void addResultToCSV(ITestResult result, ITestContext context) {
218 ExtentTest test = getExtendTest();
219 com.aventstack.extentreports.model.Test model = test.getModel();
220 String name = model.getName();
221 String status = model.getStatus().toString();
222 getCsvReport().writeRow(result.getInstanceName(), name.replace(RE_RUN, ""), status);
225 private void generateReport4Jenkins(ITestContext context) {
226 final String suiteName = ExtentManager.getSuiteName(context);
227 final JSONObject obj = new JSONObject();
228 final String success = Integer.toString(context.getPassedTests().size());
229 final String failed = Integer.toString(context.getFailedTests().size());
230 final String total = Integer.toString(context.getFailedTests().size() + context.getPassedTests().size());
231 obj.put("projectName", "SDC-ONAP-UI-Automation-" + suiteName);
232 obj.put("projectVersion", AutomationUtils.getOSVersion());
233 obj.put("platform", "Linux");
234 obj.put("total", total);
235 obj.put("success", success);
236 obj.put("failed", failed);
238 try (FileWriter file = new FileWriter(getReportFolder() + "jenkinsResults.json")) {
239 file.write(obj.toJSONString());
241 } catch (final IOException e) {
242 LOGGER.debug("An error has occurred while writing 'jenkinsResults.json' file", e);
245 LOGGER.debug(obj.toJSONString());
249 @Parameters({"eraseAfterTests"})
250 @AfterSuite(alwaysRun = true)
251 public void afterSuite2(@Optional("true") String eraseAfterTestsReadValue) throws Exception {
253 csvReport.closeFile();
254 generateReport4Jenkins(myContext);
256 if (Boolean.parseBoolean(eraseAfterTestsReadValue)) {
257 RestCDUtils.deleteOnDemand();
259 System.out.println("Resources will not be deleted according to suite configuration ...");
262 if (getConfig().getUseBrowserMobProxy()) {
263 MobProxy.getPoxyServer().stop();
267 private static String setUrl() {
268 url = getConfig().getUrl();
269 uiSimulator = getConfig().isUiSimulator();
271 String message = "no URL found";
272 System.out.println(message);
273 Assert.fail(message);
274 } else if (!url.contains("localhost") && !url.contains("192.168.33.10") && !url.contains("127.0.0.1") && !url.contains("192.168.50.5") && !uiSimulator) {
281 private static void navigateToUrl(final String url) {
283 LOGGER.info("Deleting cookies");
285 LOGGER.info("Navigating to URL : " + url);
286 getDriver().navigate().to(url);
287 GeneralUIUtils.waitForLoader();
288 LOGGER.info("Zooming out");
289 GeneralUIUtils.windowZoomOutUltimate();
290 } catch (Exception e) {
291 final String errorMsg = String.format("Could not navigate to '%s'", url);
292 LOGGER.error(errorMsg, e);
293 getExtendTest().log(Status.ERROR, errorMsg);
294 Assert.fail(errorMsg);
298 private static void deleteCookies() throws Exception {
299 getDriver().manage().deleteAllCookies();
300 Thread.sleep(BASIC_SLEEP_DURATION);
303 final int max_attempts = 3;
305 while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts) {
306 getExtendTest().log(Status.INFO, "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts");
307 String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });";
308 ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS);
311 if (attempts == max_attempts) {
312 String msg = "Did not delete cookies, can't login as user " + WindowTestManager.getWindowMap().getUser().getRole();
313 System.out.println(msg);
314 getExtendTest().log(Status.ERROR, msg);
320 private void loginToSystem(UserRoleEnum role) throws Exception {
321 final int gettingWebElementTimeOut = 30;
322 UserCredentials credentials = new UserCredentials(role.getUserId(), role.getPassword(), role.getFirstName(), role.getLastName(), role.name());
324 loginToSimulator(role);
326 sendUserAndPasswordKeys(credentials);
327 WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), gettingWebElementTimeOut);
328 submitButton.click();
329 WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), gettingWebElementTimeOut);
330 Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed.");
333 GeneralUIUtils.ultimateWait();
334 getWindowTest().setUser(credentials);
337 private void goToHomePage(UserRoleEnum role) throws Exception {
338 final int gettingButtonTimeOut = 10;
340 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() == 0 ? NUM_OF_ATTEMPTS_TO_REFTRESH : getWindowTest().getRefreshAttempts());
341 if (!role.equals(UserRoleEnum.ADMIN)) {
343 WebElement closeButton = GeneralUIUtils.getClickableButtonBy(By.className("sdc-welcome-close"), gettingButtonTimeOut);
344 if (closeButton != null) {
348 if (!GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue())) {
349 restartBrowser(role);
352 } catch (Exception e) {
353 restartBrowser(role);
357 private void restartBrowser(UserRoleEnum role) throws Exception {
358 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() - 1);
359 if (getWindowTest().getRefreshAttempts() <= 0) {
360 System.out.println("ERR : Something is wrong with browser!");
361 Assert.fail("ERR : Something is wrong with browser!");
363 System.out.println("Trying again...");
364 getExtendTest().log(Status.INFO, "Trying again...");
365 getExtendTest().log(Status.INFO, String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts()));
366 System.out.println(String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts()));
368 reloginWithNewRole(role);
371 private void loginToSimulator(UserRoleEnum role) {
372 final int gettingWebElementTimeOut = 30;
373 WebDriver driver = GeneralUIUtils.getDriver();
374 WebDriverWait wait = new WebDriverWait(driver, gettingWebElementTimeOut);
376 wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']"))));
378 WebElement userIdTextbox = GeneralUIUtils.getWebElementBy(By.name("userId"));
379 userIdTextbox.sendKeys(role.getUserId());
380 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
381 passwordTextbox.sendKeys(WEB_SEAL_PASSWORD);
383 wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click();
386 private void sendUserAndPasswordKeys(UserCredentials userId) {
387 System.out.println("Login as user : " + userId.getUserId());
388 WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid"));
389 userNameTextbox.sendKeys(userId.getUserId());
390 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
391 passwordTextbox.sendKeys(userId.getPassword());
394 private void loginWithUser(final UserRoleEnum role) {
396 final String msg = String
397 .format("Login as user '%s', role '%s'", role.getUserId(), role.getUserRole());
398 getExtendTest().log(Status.INFO, msg);
401 LOGGER.debug("Going to home page");
403 } catch (final Exception e) {
404 throw new RuntimeException(e);
406 getWindowTest().setPreviousRole(getWindowTest().getUser().getRole());
410 private void setUser(UserRoleEnum role) {
411 User user = new User();
412 user.setUserId(role.getUserId());
413 user.setFirstName(role.getFirstName());
414 user.setRole(role.name());
415 user.setLastName(role.getLastName());
417 getWindowTest().setUser(user);
420 public User getUser() {
421 return getWindowTest().getUser();
424 private void setBrowserBeforeTest(final UserRoleEnum role) {
425 LOGGER.info(String.format("Setup before test for role '%s'", role.name()));
426 if (!getWindowTest().getPreviousRole().equalsIgnoreCase(role.name())) {
427 LOGGER.info(String.format("Logging in with new role '%s'. Previous role was: '%s'.", role.name(),
428 getWindowTest().getPreviousRole()));
429 navigateAndLogin(role);
433 private void navigateAndLogin(final UserRoleEnum role) {
434 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts());
438 GeneralUIUtils.ultimateWait();
441 public User getUser(UserRoleEnum role) {
442 User user = new User();
443 user.setUserId(role.getUserId());
444 user.setFirstName(role.getFirstName());
445 user.setLastName(role.getLastName());
446 user.setRole(role.name());
450 protected void reloginWithNewRole(final UserRoleEnum role) {
451 navigateAndLogin(role);
454 private void addTrafficFileToReport(ITestResult result) {
457 Har har = MobProxy.getPoxyServer().getHar();
458 String shortUUID = UUID.randomUUID().toString().split("-")[0];
459 File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har");
460 new File(getHarFilesFolder()).mkdirs();
462 har.writeTo(harFile);
464 String pathToFileFromReportDirectory = HAR_FILES_FOLDER_NAME + File.separator + harFile.getName();
465 ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory, "File with captured traffic");
466 } catch (IOException ioe) {
467 ioe.printStackTrace();
472 * * Start section of test in ExtentReport with DataProvider parameters,
473 * should be started from test method, see example in onboardVNFTest
475 public void setLog(String fromDataProvider) {
477 String suiteName = ExtentManager.getSuiteName(myContext);
478 if (ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName)) {
479 ExtentTestManager.getInstance().startTest(RE_RUN + Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
481 ExtentTestManager.getInstance().startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
485 getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
486 ExtentTestManager.getInstance().assignCategory(this.getClass());
487 setBrowserBeforeTest(getRole());