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;
28 import java.io.FileWriter;
29 import java.io.IOException;
30 import java.util.Arrays;
31 import java.util.UUID;
32 import net.lightbody.bmp.core.har.Har;
33 import org.json.simple.JSONObject;
34 import org.onap.sdc.backend.ci.tests.config.UserCredentialsFromFile;
35 import org.onap.sdc.frontend.ci.tests.datatypes.DataTestIdEnum;
36 import org.onap.sdc.frontend.ci.tests.datatypes.UserCredentials;
37 import org.onap.sdc.frontend.ci.tests.execute.sanity.OnboardingFlowsUi;
38 import org.onap.sdc.frontend.ci.tests.pages.HomePage;
39 import org.onap.sdc.frontend.ci.tests.utilities.FileHandling;
40 import org.onap.sdc.frontend.ci.tests.utilities.GeneralUIUtils;
41 import org.onap.sdc.frontend.ci.tests.utilities.RestCDUtils;
42 import org.onap.sdc.backend.ci.tests.utils.rest.AutomationUtils;
43 import org.openecomp.sdc.be.model.User;
44 import org.onap.sdc.backend.ci.tests.datatypes.enums.UserRoleEnum;
45 import org.openqa.selenium.By;
46 import org.openqa.selenium.JavascriptExecutor;
47 import org.openqa.selenium.WebDriver;
48 import org.openqa.selenium.WebElement;
49 import org.openqa.selenium.support.ui.ExpectedConditions;
50 import org.openqa.selenium.support.ui.WebDriverWait;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.testng.Assert;
54 import org.testng.ITestContext;
55 import org.testng.ITestResult;
56 import org.testng.annotations.AfterMethod;
57 import org.testng.annotations.AfterSuite;
58 import org.testng.annotations.BeforeMethod;
59 import org.testng.annotations.BeforeSuite;
60 import org.testng.annotations.Optional;
61 import org.testng.annotations.Parameters;
62 import org.testng.annotations.Test;
64 public abstract class SetupCDTest extends DriverFactory {
66 private static final Logger LOGGER = LoggerFactory.getLogger(SetupCDTest.class);
68 private static final String RE_RUN = "<html><font color=\"red\">ReRun - </font></html>";
69 private static final String WEB_SEAL_PASSWORD = "123123a";
70 protected static final String HEAT_FILE_YAML_NAME_PREFIX = "Heat-File";
71 protected static final String HEAT_FILE_YAML_NAME_SUFFIX = ".yaml";
72 private static final int BASIC_SLEEP_DURATION = 1000;
74 /**************** CONSTANTS ****************/
75 private static final String CREDENTIALS_FILE = "credentials.yaml";
77 private static final String REPORT_FILE_NAME = "SDC_UI_Extent_Report.html";
78 private static final String REPORT_FOLDER = "target" + File.separator + "ExtentReport" + File.separator;
79 private static final String SCREENSHOT_FOLDER = REPORT_FOLDER + "screenshots" + File.separator;
80 private static final String HAR_FILES_FOLDER_NAME = "har_files";
81 private 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";
85 private static final int NUM_OF_ATTEMPTS_TO_REFTRESH = 2;
87 /**************** PRIVATES ****************/
88 private static String url;
90 private static boolean uiSimulator;
91 private static boolean localEnv = true;
92 private static OnboardCSVReport csvReport;
93 private final UserCredentialsFromFile credentialsIns = UserCredentialsFromFile.getInstance();
94 private static ITestContext myContext;
96 public SetupCDTest() {
97 LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
98 lc.getLogger("org.apache").setLevel(Level.INFO);
101 public static ExtentTest getExtendTest() {
102 return ExtentTestManager.getInstance().getTest();
105 public static WindowTest getWindowTest() {
106 return WindowTestManager.getWindowMap();
109 private OnboardCSVReport getCsvReport() {
113 public static String getReportFolder() {
114 return REPORT_FOLDER;
117 public static String getScreenshotFolder() {
118 return SCREENSHOT_FOLDER;
121 private static String getHarFilesFolder() {
122 return HAR_FILES_FOLDER;
126 protected abstract UserRoleEnum getRole();
128 /**************** BEFORE ****************/
130 @BeforeSuite(alwaysRun = true)
131 public void setupBeforeSuite(ITestContext context) throws Exception {
132 RestCDUtils.deleteOnDemand();
135 ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
136 csvReport = new OnboardCSVReport(getReportFolder(), SHORT_CSV_REPORT_FILE_NAME);
139 @BeforeMethod(alwaysRun = true)
140 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
142 boolean emptyDataProvider = method.getAnnotation(Test.class).dataProvider().isEmpty();
143 String className = method.getDeclaringClass().getName();
144 if (emptyDataProvider && !className.contains("ToscaValidationTest")) {
145 System.out.println("ExtentReport instance started from BeforeMethod...");
146 String suiteName = ExtentManager.getSuiteName(context);
147 if (suiteName.equals(ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
148 ExtentTestManager.getInstance().startTest(RE_RUN + method.getName());
150 ExtentTestManager.getInstance().startTest(method.getName());
153 ExtentTestManager.getInstance().assignCategory(this.getClass());
154 setBrowserBeforeTest(getRole());
156 System.out.println("ExtentReport instance started from Test...");
159 if (getConfig().getCaptureTraffic()) {
161 MobProxy.getPoxyServer().newHar(method.getName() + ".har");
162 } catch (Throwable e) {
168 /**************** AFTER ****************/
169 @AfterMethod(alwaysRun = true)
170 public void quitAfterTest(final ITestResult result, final ITestContext context) throws Exception {
172 ReportAfterTestManager.report(result, context);
173 GeneralUIUtils.closeErrorMessage();
176 if (getConfig().getCaptureTraffic()) {
177 addTrafficFileToReport(result);
180 if (result.getInstanceName().equals(OnboardingFlowsUi.class.getName()) && result.getStatus() == ITestResult.FAILURE) {
181 final String msg = "Onboarding test failed, closing browser";
183 getExtendTest().log(Status.INFO, msg);
185 } else if (!getUser().getRole().toLowerCase().equals(UserRoleEnum.ADMIN.name().toLowerCase())) {
186 boolean navigateToHomePageSuccess = HomePage.navigateToHomePage();
187 if (!navigateToHomePageSuccess) {
188 final String msg = "Navigating to homepage failed, reopening driver";
190 getExtendTest().log(Status.INFO, msg);
195 } catch (final Exception e) {
196 LOGGER.error("An unexpected error has occurred", e);
197 getExtendTest().log(Status.ERROR, "Exception:" + e.toString());
201 ExtentTestManager.getInstance().endTest();
202 final String suiteName = ExtentManager.getSuiteName(context);
203 // write result to csv file
204 if ((!ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName)) && (result.getStatus() == ITestResult.SKIP)) {
205 addResultToCSV(result, context);
207 if (ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName) && !(result.getStatus() == ITestResult.SUCCESS)) {
208 addResultToCSV(result, context);
210 FileHandling.cleanCurrentDownloadDir();
215 private void addResultToCSV(ITestResult result, ITestContext context) {
216 ExtentTest test = getExtendTest();
217 com.aventstack.extentreports.model.Test model = test.getModel();
218 String name = model.getName();
219 String status = model.getStatus().toString();
220 getCsvReport().writeRow(result.getInstanceName(), name.replace(RE_RUN, ""), status);
223 private void generateReport4Jenkins(ITestContext context) {
224 final String suiteName = ExtentManager.getSuiteName(context);
225 final JSONObject obj = new JSONObject();
226 final String success = Integer.toString(context.getPassedTests().size());
227 final String failed = Integer.toString(context.getFailedTests().size());
228 final String total = Integer.toString(context.getFailedTests().size() + context.getPassedTests().size());
229 obj.put("projectName", "SDC-ONAP-UI-Automation-" + suiteName);
230 obj.put("projectVersion", AutomationUtils.getOSVersion());
231 obj.put("platform", "Linux");
232 obj.put("total", total);
233 obj.put("success", success);
234 obj.put("failed", failed);
236 try (FileWriter file = new FileWriter(getReportFolder() + "jenkinsResults.json")) {
237 file.write(obj.toJSONString());
239 } catch (final IOException e) {
240 LOGGER.debug("An error has occurred while writing 'jenkinsResults.json' file", e);
243 LOGGER.debug(obj.toJSONString());
247 @Parameters({"eraseAfterTests"})
248 @AfterSuite(alwaysRun = true)
249 public void afterSuite2(@Optional("true") String eraseAfterTestsReadValue) throws Exception {
251 csvReport.closeFile();
252 generateReport4Jenkins(myContext);
254 if (Boolean.parseBoolean(eraseAfterTestsReadValue)) {
255 RestCDUtils.deleteOnDemand();
257 System.out.println("Resources will not be deleted according to suite configuration ...");
260 if (getConfig().getUseBrowserMobProxy()) {
261 MobProxy.getPoxyServer().stop();
265 private static String setUrl() {
266 url = getConfig().getUrl();
267 uiSimulator = getConfig().isUiSimulator();
269 String message = "no URL found";
270 System.out.println(message);
271 Assert.fail(message);
272 } else if (!url.contains("localhost") && !url.contains("192.168.33.10") && !url.contains("127.0.0.1") && !url.contains("192.168.50.5") && !uiSimulator) {
279 private static void navigateToUrl(final String url) {
281 LOGGER.info("Deleting cookies");
283 LOGGER.info("Navigating to URL : " + url);
284 getDriver().navigate().to(url);
285 GeneralUIUtils.waitForLoader();
286 LOGGER.info("Zooming out");
287 GeneralUIUtils.windowZoomOutUltimate();
288 } catch (Exception e) {
289 final String errorMsg = String.format("Could not navigate to '%s'", url);
290 LOGGER.error(errorMsg, e);
291 getExtendTest().log(Status.ERROR, errorMsg);
292 Assert.fail(errorMsg);
296 private static void deleteCookies() throws Exception {
297 getDriver().manage().deleteAllCookies();
298 Thread.sleep(BASIC_SLEEP_DURATION);
301 final int max_attempts = 3;
303 while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts) {
304 getExtendTest().log(Status.INFO, "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts");
305 String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });";
306 ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS);
309 if (attempts == max_attempts) {
310 String msg = "Did not delete cookies, can't login as user " + WindowTestManager.getWindowMap().getUser().getRole();
311 System.out.println(msg);
312 getExtendTest().log(Status.ERROR, msg);
318 private void loginToSystem(UserRoleEnum role) throws Exception {
319 final int gettingWebElementTimeOut = 30;
320 UserCredentials credentials = new UserCredentials(role.getUserId(), role.getPassword(), role.getFirstName(), role.getLastName(), role.name());
322 loginToSimulator(role);
324 sendUserAndPasswordKeys(credentials);
325 WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), gettingWebElementTimeOut);
326 submitButton.click();
327 WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), gettingWebElementTimeOut);
328 Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed.");
331 GeneralUIUtils.ultimateWait();
332 getWindowTest().setUser(credentials);
335 private void goToHomePage(UserRoleEnum role) throws Exception {
336 final int gettingButtonTimeOut = 10;
338 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() == 0 ? NUM_OF_ATTEMPTS_TO_REFTRESH : getWindowTest().getRefreshAttempts());
339 if (!role.equals(UserRoleEnum.ADMIN)) {
341 WebElement closeButton = GeneralUIUtils.getClickableButtonBy(By.className("sdc-welcome-close"), gettingButtonTimeOut);
342 if (closeButton != null) {
346 if (!GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue())) {
347 restartBrowser(role);
350 } catch (Exception e) {
351 restartBrowser(role);
355 private void restartBrowser(UserRoleEnum role) throws Exception {
356 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() - 1);
357 if (getWindowTest().getRefreshAttempts() <= 0) {
358 System.out.println("ERR : Something is wrong with browser!");
359 Assert.fail("ERR : Something is wrong with browser!");
361 System.out.println("Trying again...");
362 getExtendTest().log(Status.INFO, "Trying again...");
363 getExtendTest().log(Status.INFO, String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts()));
364 System.out.println(String.format("%s attempt(s) left", getWindowTest().getRefreshAttempts()));
366 reloginWithNewRole(role);
369 private void loginToSimulator(UserRoleEnum role) {
370 final int gettingWebElementTimeOut = 30;
371 WebDriver driver = GeneralUIUtils.getDriver();
372 WebDriverWait wait = new WebDriverWait(driver, gettingWebElementTimeOut);
374 wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']"))));
376 WebElement userIdTextbox = GeneralUIUtils.getWebElementBy(By.name("userId"));
377 userIdTextbox.sendKeys(role.getUserId());
378 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
379 passwordTextbox.sendKeys(WEB_SEAL_PASSWORD);
381 wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click();
384 private void sendUserAndPasswordKeys(UserCredentials userId) {
385 System.out.println("Login as user : " + userId.getUserId());
386 WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid"));
387 userNameTextbox.sendKeys(userId.getUserId());
388 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
389 passwordTextbox.sendKeys(userId.getPassword());
392 private void loginWithUser(final UserRoleEnum role) {
394 final String msg = String
395 .format("Login as user '%s', role '%s'", role.getUserId(), role.getUserRole());
396 getExtendTest().log(Status.INFO, msg);
399 LOGGER.debug("Going to home page");
401 } catch (final Exception e) {
402 throw new RuntimeException(e);
404 getWindowTest().setPreviousRole(getWindowTest().getUser().getRole());
408 private void setUser(UserRoleEnum role) {
409 User user = new User();
410 user.setUserId(role.getUserId());
411 user.setFirstName(role.getFirstName());
412 user.setRole(role.name());
413 user.setLastName(role.getLastName());
415 getWindowTest().setUser(user);
418 public User getUser() {
419 return getWindowTest().getUser();
422 private void setBrowserBeforeTest(final UserRoleEnum role) {
423 LOGGER.info(String.format("Setup before test for role '%s'", role.name()));
424 if (!getWindowTest().getPreviousRole().equalsIgnoreCase(role.name())) {
425 LOGGER.info(String.format("Logging in with new role '%s'. Previous role was: '%s'.", role.name(),
426 getWindowTest().getPreviousRole()));
427 navigateAndLogin(role);
431 private void navigateAndLogin(final UserRoleEnum role) {
432 getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts());
436 GeneralUIUtils.ultimateWait();
439 public User getUser(UserRoleEnum role) {
440 User user = new User();
441 user.setUserId(role.getUserId());
442 user.setFirstName(role.getFirstName());
443 user.setLastName(role.getLastName());
444 user.setRole(role.name());
448 protected void reloginWithNewRole(final UserRoleEnum role) {
449 navigateAndLogin(role);
452 private void addTrafficFileToReport(ITestResult result) {
455 Har har = MobProxy.getPoxyServer().getHar();
456 String shortUUID = UUID.randomUUID().toString().split("-")[0];
457 File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har");
458 new File(getHarFilesFolder()).mkdirs();
460 har.writeTo(harFile);
462 String pathToFileFromReportDirectory = HAR_FILES_FOLDER_NAME + File.separator + harFile.getName();
463 ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory, "File with captured traffic");
464 } catch (IOException ioe) {
465 ioe.printStackTrace();
470 * * Start section of test in ExtentReport with DataProvider parameters,
471 * should be started from test method, see example in onboardVNFTest
473 public void setLog(String fromDataProvider) {
475 String suiteName = ExtentManager.getSuiteName(myContext);
476 if (ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName)) {
477 ExtentTestManager.getInstance().startTest(RE_RUN + Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
479 ExtentTestManager.getInstance().startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + " " + fromDataProvider);
483 getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
484 ExtentTestManager.getInstance().assignCategory(this.getClass());
485 setBrowserBeforeTest(getRole());