9f5a7cc7cd6cd5d5de36b091af8bd93fea10f656
[sdc.git] / integration-tests / src / test / java / org / onap / sdc / frontend / ci / tests / execute / setup / SetupCDTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.onap.sdc.frontend.ci.tests.execute.setup;
22
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 java.io.File;
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;
63
64 public abstract class SetupCDTest extends DriverFactory {
65
66     private static final Logger LOGGER = LoggerFactory.getLogger(SetupCDTest.class);
67
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;
73
74     /**************** CONSTANTS ****************/
75     private static final String CREDENTIALS_FILE = "credentials.yaml";
76
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;
82
83     private static final String SHORT_CSV_REPORT_FILE_NAME = "ShortReport.csv";
84
85     private static final int NUM_OF_ATTEMPTS_TO_REFTRESH = 2;
86
87     /**************** PRIVATES ****************/
88     private static String url;
89
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;
95
96     public SetupCDTest() {
97         LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
98         lc.getLogger("org.apache").setLevel(Level.INFO);
99     }
100
101     public static ExtentTest getExtendTest() {
102         return ExtentTestManager.getInstance().getTest();
103     }
104
105     public static WindowTest getWindowTest() {
106         return WindowTestManager.getWindowMap();
107     }
108
109     private OnboardCSVReport getCsvReport() {
110         return csvReport;
111     }
112
113     public static String getReportFolder() {
114         return REPORT_FOLDER;
115     }
116
117     public static String getScreenshotFolder() {
118         return SCREENSHOT_FOLDER;
119     }
120
121     private static String getHarFilesFolder() {
122         return HAR_FILES_FOLDER;
123     }
124
125
126     protected abstract UserRoleEnum getRole();
127
128     /**************** BEFORE ****************/
129
130     @BeforeSuite(alwaysRun = true)
131     public void setupBeforeSuite(ITestContext context) throws Exception {
132         RestCDUtils.deleteOnDemand();
133         myContext = context;
134         setUrl();
135         ExtentManager.initReporter(getReportFolder(), REPORT_FILE_NAME, context);
136         csvReport = new OnboardCSVReport(getReportFolder(), SHORT_CSV_REPORT_FILE_NAME);
137     }
138
139     @BeforeMethod(alwaysRun = true)
140     public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
141
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());
149             } else {
150                 ExtentTestManager.getInstance().startTest(method.getName());
151             }
152
153             ExtentTestManager.getInstance().assignCategory(this.getClass());
154             setBrowserBeforeTest(getRole());
155         } else {
156             System.out.println("ExtentReport instance started from Test...");
157         }
158
159         if (getConfig().getCaptureTraffic()) {
160             try {
161                 MobProxy.getPoxyServer().newHar(method.getName() + ".har");
162             } catch (Throwable e) {
163                 e.printStackTrace();
164             }
165         }
166     }
167
168     /**************** AFTER ****************/
169     @AfterMethod(alwaysRun = true)
170     public void quitAfterTest(final ITestResult result, final ITestContext context) throws Exception {
171         try {
172             ReportAfterTestManager.report(result, context);
173             GeneralUIUtils.closeErrorMessage();
174         } finally {
175             try {
176                 if (getConfig().getCaptureTraffic()) {
177                     addTrafficFileToReport(result);
178                 }
179
180                 if (result.getInstanceName().equals(OnboardingFlowsUi.class.getName()) && result.getStatus() == ITestResult.FAILURE) {
181                     final String msg = "Onboarding test failed, closing browser";
182                     LOGGER.info(msg);
183                     getExtendTest().log(Status.INFO, msg);
184                     quitDriver();
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";
189                         LOGGER.info(msg);
190                         getExtendTest().log(Status.INFO, msg);
191                         quitDriver();
192                     }
193                 }
194
195             } catch (final Exception e) {
196                 LOGGER.error("An unexpected error has occurred", e);
197                 getExtendTest().log(Status.ERROR, "Exception:" + e.toString());
198             }
199
200
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);
206             }
207             if (ExtentManager.suiteNameXml.TESTNG_FAILED_XML_NAME.getValue().equals(suiteName) && !(result.getStatus() == ITestResult.SUCCESS)) {
208                 addResultToCSV(result, context);
209             }
210             FileHandling.cleanCurrentDownloadDir();
211         }
212
213     }
214
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);
221     }
222
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);
235
236         try (FileWriter file = new FileWriter(getReportFolder() + "jenkinsResults.json")) {
237             file.write(obj.toJSONString());
238             file.flush();
239         } catch (final IOException e) {
240             LOGGER.debug("An error has occurred while writing 'jenkinsResults.json' file", e);
241         }
242
243         LOGGER.debug(obj.toJSONString());
244     }
245
246
247     @Parameters({"eraseAfterTests"})
248     @AfterSuite(alwaysRun = true)
249     public void afterSuite2(@Optional("true") String eraseAfterTestsReadValue) throws Exception {
250
251         csvReport.closeFile();
252         generateReport4Jenkins(myContext);
253
254         if (Boolean.parseBoolean(eraseAfterTestsReadValue)) {
255             RestCDUtils.deleteOnDemand();
256         } else {
257             System.out.println("Resources will not be deleted according to suite configuration ...");
258         }
259
260         if (getConfig().getUseBrowserMobProxy()) {
261             MobProxy.getPoxyServer().stop();
262         }
263     }
264
265     private static String setUrl() {
266         url = getConfig().getUrl();
267         uiSimulator = getConfig().isUiSimulator();
268         if (url == null) {
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) {
273             localEnv = false;
274         }
275         return url;
276     }
277
278
279     private static void navigateToUrl(final String url) {
280         try {
281             LOGGER.info("Deleting cookies");
282             deleteCookies();
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);
293         }
294     }
295
296     private static void deleteCookies() throws Exception {
297         getDriver().manage().deleteAllCookies();
298         Thread.sleep(BASIC_SLEEP_DURATION);
299
300         int attempts = 0;
301         final int max_attempts = 3;
302
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);
307             attempts++;
308
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);
313                 Assert.fail(msg);
314             }
315         }
316     }
317
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());
321         if (localEnv) {
322             loginToSimulator(role);
323         } else {
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.");
329             buttonOK.click();
330         }
331         GeneralUIUtils.ultimateWait();
332         getWindowTest().setUser(credentials);
333     }
334
335     private void goToHomePage(UserRoleEnum role) throws Exception {
336         final int gettingButtonTimeOut = 10;
337         try {
338             getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts() == 0 ? NUM_OF_ATTEMPTS_TO_REFTRESH : getWindowTest().getRefreshAttempts());
339             if (!role.equals(UserRoleEnum.ADMIN)) {
340
341                 WebElement closeButton = GeneralUIUtils.getClickableButtonBy(By.className("sdc-welcome-close"), gettingButtonTimeOut);
342                 if (closeButton != null) {
343                     closeButton.click();
344                 }
345
346                 if (!GeneralUIUtils.isElementVisibleByTestId(DataTestIdEnum.MainMenuButtons.HOME_BUTTON.getValue())) {
347                     restartBrowser(role);
348                 }
349             }
350         } catch (Exception e) {
351             restartBrowser(role);
352         }
353     }
354
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!");
360         }
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()));
365
366         reloginWithNewRole(role);
367     }
368
369     private void loginToSimulator(UserRoleEnum role) {
370         final int gettingWebElementTimeOut = 30;
371         WebDriver driver = GeneralUIUtils.getDriver();
372         WebDriverWait wait = new WebDriverWait(driver, gettingWebElementTimeOut);
373
374         wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//*[@method='" + "post" + "']"))));
375
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);
380
381         wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//*[@value='" + "Login" + "']")))).click();
382     }
383
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());
390     }
391
392     private void loginWithUser(final UserRoleEnum role) {
393         try {
394             final String msg = String
395                 .format("Login as user '%s', role '%s'", role.getUserId(), role.getUserRole());
396             getExtendTest().log(Status.INFO, msg);
397             LOGGER.info(msg);
398             loginToSystem(role);
399             LOGGER.debug("Going to home page");
400             goToHomePage(role);
401         } catch (final Exception e) {
402             throw new RuntimeException(e);
403         } finally {
404             getWindowTest().setPreviousRole(getWindowTest().getUser().getRole());
405         }
406     }
407
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());
414
415         getWindowTest().setUser(user);
416     }
417
418     public User getUser() {
419         return getWindowTest().getUser();
420     }
421
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);
428         }
429     }
430
431     private void navigateAndLogin(final UserRoleEnum role) {
432         getWindowTest().setRefreshAttempts(getWindowTest().getRefreshAttempts());
433         setUser(role);
434         navigateToUrl(url);
435         loginWithUser(role);
436         GeneralUIUtils.ultimateWait();
437     }
438
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());
445         return user;
446     }
447
448     protected void reloginWithNewRole(final UserRoleEnum role) {
449         navigateAndLogin(role);
450     }
451
452     private void addTrafficFileToReport(ITestResult result) {
453         try {
454             // Get the HAR data
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();
459
460             har.writeTo(harFile);
461
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();
466         }
467     }
468
469     /*
470      * * Start section of test in ExtentReport with DataProvider parameters,
471      * should be started from test method, see example in onboardVNFTest
472      */
473     public void setLog(String fromDataProvider) {
474
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() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
478         } else {
479             ExtentTestManager.getInstance().startTest(Thread.currentThread().getStackTrace()[2].getMethodName() + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + fromDataProvider);
480         }
481
482
483         getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
484         ExtentTestManager.getInstance().assignCategory(this.getClass());
485         setBrowserBeforeTest(getRole());
486     }
487 }