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