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.ci.tests.execute.setup;
23 import com.aventstack.extentreports.ExtentTest;
24 import com.aventstack.extentreports.Status;
26 import java.io.IOException;
27 import java.util.UUID;
28 import net.lightbody.bmp.core.har.Har;
29 import org.onap.sdc.ci.tests.datatypes.Configuration;
30 import org.onap.sdc.ci.tests.datatypes.User;
31 import org.onap.sdc.ci.tests.datatypes.UserCredentials;
32 import org.onap.sdc.ci.tests.datatypes.UserRoleEnum;
33 import org.onap.sdc.ci.tests.execute.setup.ExtentManager.suiteNameXml;
34 import org.onap.sdc.ci.tests.run.StartTest;
35 import org.onap.sdc.ci.tests.utilities.FileHandling;
36 import org.onap.sdc.ci.tests.utilities.GeneralUIUtils;
37 import org.openqa.selenium.By;
38 import org.openqa.selenium.JavascriptExecutor;
39 import org.openqa.selenium.WebElement;
40 import org.testng.Assert;
41 import org.testng.ITestContext;
42 import org.testng.ITestResult;
43 import org.testng.annotations.AfterMethod;
44 import org.testng.annotations.AfterSuite;
45 import org.testng.annotations.BeforeMethod;
46 import org.testng.annotations.BeforeSuite;
47 import org.testng.annotations.Test;
49 public abstract class SetupCDTest extends DriverFactory {
51 private static final String RE_RUN = "<html><font color=\"red\">ReRun - </font></html>";
53 /**************** PRIVATES ****************/
54 private static String url;
56 protected static ITestContext myContext;
58 /**************** METHODS ****************/
59 public static ExtentTest getExtendTest() {
60 return ExtentTestManager.getTest();
63 public static WindowTest getWindowTest() {
64 return WindowTestManager.getWindowMap();
67 public static String getScreenshotFolder() {
68 return getConfiguration().getScreenshotFolder();
71 public static String getHarFilesFolder() {
72 return getConfiguration().getHarFilesFolder();
75 public static String getReportFolder(){
76 return getConfiguration().getReportFolder();
79 public static String getReportFilename(){
80 return getConfiguration().getReportFileName();
83 protected abstract UserCredentials getUserCredentials();
84 protected abstract Configuration getEnvConfiguration();
85 protected abstract void loginToLocalSimulator(UserCredentials userCredentials);
89 /**************** BEFORE ****************/
91 @BeforeSuite(alwaysRun = true)
92 public void setupBeforeSuite(ITestContext context) throws Exception {
97 private void initReport(ITestContext context) throws Exception {
99 ExtentManager.initReporter(getConfiguration(), context);
102 @BeforeMethod(alwaysRun = true)
103 public void setBrowserBeforeTest(java.lang.reflect.Method method, ITestContext context) throws Exception {
104 boolean emptyDataProvider = isDataProviderEmpty(method);
105 if (emptyDataProvider) {
106 System.out.println("ExtentReport instance started from BeforeMethod...");
107 String suiteName = ExtentManager.getSuiteName(context);
108 if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
109 ExtentTestManager.startTest(RE_RUN + method.getName());
111 ExtentTestManager.startTest(method.getName());
114 ExtentTestManager.assignCategory(this.getClass());
115 setBrowserBeforeTest(getUserCredentials());
117 System.out.println("ExtentReport instance started from Test...");
120 getConfiguration().setWindowsDownloadDirectory(getWindowTest().getDownloadDirectory());
122 if (getConfiguration().isCaptureTraffic()) {
124 MobProxy.getPoxyServer().newHar(method.getName() + ".har");
125 } catch (Throwable e) {
131 private boolean isDataProviderEmpty(java.lang.reflect.Method method) {
132 return method.getAnnotation(Test.class).dataProvider().isEmpty();
135 /**************** AFTER ****************/
136 @AfterMethod(alwaysRun = true)
137 public void quitAfterTest(ITestResult result, ITestContext context) throws Exception {
140 ReportAfterTestManager.report(result, context);
141 GeneralUIUtils.closeErrorMessage();
144 if (getConfiguration().isCaptureTraffic()) {
145 // addTrafficFileToReport(result);
148 ExtentTestManager.endTest();
149 ExtentManager.closeReporter();
150 FileHandling.cleanCurrentDownloadDir();
155 @AfterSuite(alwaysRun = true)
156 public void afterSuite() throws Exception {
157 if (getConfiguration().isUseBrowserMobProxy()) {
158 MobProxy.getPoxyServer().stop();
162 protected static String setUrl() {
163 url = getConfiguration().getUrl();
165 String message = "no URL found";
166 System.out.println(message);
167 Assert.fail(message);
172 public static void navigateToUrl(String url) {
174 System.out.println("Navigating to URL : " + url);
175 getDriver().navigate().to(url);
176 GeneralUIUtils.waitForLoader();
178 System.out.println("Zooming out...");
179 GeneralUIUtils.windowZoomOutUltimate();
181 } catch (Exception e) {
182 String msg = "Browser is unreachable";
183 System.out.println(msg);
185 getExtendTest().log(Status.ERROR, msg);
190 private static void deleteCookies() throws Exception {
191 getDriver().manage().deleteAllCookies();
195 final int max_attempts = 3;
197 while (!getDriver().manage().getCookies().isEmpty() && attempts < max_attempts) {
198 getExtendTest().log(Status.INFO,
199 "Trying to delete cookies one more time - " + (attempts + 1) + "/" + max_attempts + "attempts");
200 String deleteCookiesJS = "document.cookie.split(';').forEach(function(c) { document.cookie = c.replace(/^ +/, '').replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/'); });";
201 ((JavascriptExecutor) getDriver()).executeScript(deleteCookiesJS);
204 if (attempts == max_attempts) {
205 String msg = "Did not delete cookies, can't login with the userId "
206 + WindowTestManager.getWindowMap().getUserCredentials().getUserId();
207 System.out.println(msg);
208 getExtendTest().log(Status.ERROR, msg);
214 protected void loginToSystem(UserCredentials userCredentials) throws Exception {
215 if (getConfiguration().isUseCustomLogin()) {
216 loginToLocalSimulator(userCredentials);
219 sendUserAndPasswordKeys(userCredentials);
220 WebElement submitButton = GeneralUIUtils.getWebElementBy(By.name("btnSubmit"), 30);
221 submitButton.click();
222 WebElement buttonOK = GeneralUIUtils.getWebElementBy(By.name("successOK"), 30);
223 Assert.assertTrue(buttonOK.isDisplayed(), "OK button is not displayed.");
226 GeneralUIUtils.ultimateWait();
227 getWindowTest().setUserCredentials(userCredentials);
230 private void setRefreshAttempts(int refreshAttempts) {
231 getWindowTest().setRefreshAttempts(refreshAttempts);
234 private void sendUserAndPasswordKeys(UserCredentials userCredentials) {
235 System.out.println("Login with the userId : " + userCredentials.getUserId());
236 WebElement userNameTextbox = GeneralUIUtils.getWebElementBy(By.name("userid"));
237 userNameTextbox.sendKeys(userCredentials.getUserId());
238 WebElement passwordTextbox = GeneralUIUtils.getWebElementBy(By.name("password"));
239 passwordTextbox.sendKeys(userCredentials.getPassword());
242 public void loginWithUser(UserCredentials userCredentials) {
244 getExtendTest().log(Status.INFO, String.format("Login with the userId %s", userCredentials.getUserId()));
245 loginToSystem(userCredentials);
246 } catch (Exception e) {
247 throw new RuntimeException(e);
249 getWindowTest().setPreviousUser(getWindowTest().getUserCredentials().getUserId());
253 private void setUser(UserCredentials userCredentials) {
254 User user = new User();
255 user.setUserId(userCredentials.getUserId());
256 user.setFirstName(userCredentials.getFirstName());
257 user.setRole(userCredentials.getRole());
258 user.setLastName(userCredentials.getLastName());
259 getWindowTest().setUserCredentials(userCredentials);
262 public User getUser() {
263 return getWindowTest().getUserCredentials();
266 private void setBrowserBeforeTest(UserCredentials userCredentials) {
267 System.out.println(String.format("Setup before test with the userId %s.", userCredentials.getUserId()));
269 System.out.println("Previous userId is : " + getWindowTest().getPreviousUser() + " ; Current userId is : " + userCredentials.getUserId());
270 if (!getWindowTest().getPreviousUser().toLowerCase().equals(userCredentials.getUserId())) {
271 System.out.println("User IDs are different. navigating and login.");
272 navigateAndLogin(userCredentials);
274 } catch (Exception e) {
279 public void navigateAndLogin(UserCredentials userCredentials) {
280 int refreshAttempts = getWindowTest().getRefreshAttempts() != 0 ? getWindowTest().getRefreshAttempts() : 0;
281 setRefreshAttempts(refreshAttempts);
282 setUser(userCredentials);
284 loginWithUser(userCredentials);
285 GeneralUIUtils.ultimateWait();
288 public User getUser(UserRoleEnum role) {
289 User user = new User();
290 user.setUserId(role.getUserId());
291 user.setFirstName(role.getFirstName());
292 user.setLastName(role.getLastName());
293 user.setRole(role.name());
297 protected void reloginWithNewRole(UserCredentials userCredentials) {
298 System.out.println(String.format("Setup before relogin with the userId %s", userCredentials.getUserId()));
299 navigateAndLogin(userCredentials);
302 public void addTrafficFileToReport(ITestResult result) {
305 Har har = MobProxy.getPoxyServer().getHar();
306 String shortUUID = UUID.randomUUID().toString().split("-")[0];
307 File harFile = new File(getHarFilesFolder() + result.getName() + shortUUID + ".har");
308 new File(getHarFilesFolder()).mkdirs();
310 har.writeTo(harFile);
312 String pathToFileFromReportDirectory = getReportFolder() + File.separator + harFile.getName();
313 ExtentTestActions.addFileToReportAsLink(harFile, pathToFileFromReportDirectory,
314 "File with captured traffic");
315 } catch (IOException ioe) {
316 ioe.printStackTrace();
321 * * Start section of test in ExtentReport with DataProvider parameters,
322 * should be started from test method, see example in onboardVNFTest
324 public void setLog(String fromDataProvider) {
326 String suiteName = ExtentManager.getSuiteName(myContext);
327 if (suiteName.equals(suiteNameXml.TESTNG_FAILED_XML_NAME.getValue())) {
328 ExtentTestManager.startTest(RE_RUN + Thread.currentThread().getStackTrace()[2].getMethodName()
329 + " " + fromDataProvider);
331 ExtentTestManager.startTest(Thread.currentThread().getStackTrace()[2].getMethodName()
332 + " " + fromDataProvider);
335 getWindowTest().setAddedValueFromDataProvider(fromDataProvider);
336 ExtentTestManager.assignCategory(this.getClass());
337 setBrowserBeforeTest(getUserCredentials());
340 public static void main(String[] args) {
341 System.out.println("---------------------");
342 System.out.println("running test from CLI");
343 System.out.println("---------------------");
345 String testSuite = System.getProperty("testSuite");
346 String[] testSuiteArr = {testSuite};
347 StartTest.main(testSuiteArr);