├── run.bat ├── src ├── test │ ├── resource │ │ └── data │ │ │ └── TestData.xlsx │ └── java │ │ └── com │ │ └── automationpractice │ │ └── runner │ │ ├── TestRunner.java │ │ └── TestBase.java └── main │ ├── java │ └── com │ │ └── automationpractice │ │ ├── utility │ │ ├── GlobalVariable.java │ │ ├── DateUtility.java │ │ ├── ConfigReader.java │ │ ├── ResourceUtility.java │ │ ├── ReportManager.java │ │ ├── ScreenshotUtility.java │ │ ├── DriverManager.java │ │ ├── AllureConfigurator.java │ │ ├── Log.java │ │ ├── ExcelUtility.java │ │ └── ElementOperations.java │ │ ├── modules │ │ ├── HomePageModule.java │ │ ├── SearchPageModule.java │ │ ├── OrderPageModule.java │ │ ├── MyAccountPageModule.java │ │ ├── LoginPageModule.java │ │ └── CreateAccountPageModule.java │ │ ├── listener │ │ ├── RetryFailedTestCases.java │ │ ├── RetryListener.java │ │ ├── Listener.java │ │ └── WebDriverListener.java │ │ ├── pageobjects │ │ ├── MyAccountPageObject.java │ │ ├── LoginPageObject.java │ │ ├── SearchPageObject.java │ │ ├── OrderPageObject.java │ │ ├── HomePageObject.java │ │ └── CreateAccountPageObject.java │ │ └── scripts │ │ ├── LoginScript.java │ │ ├── CreateAccountScript.java │ │ └── ProductCheckoutScript.java │ └── resources │ └── log4j2.xml ├── testng.xml ├── .gitignore ├── config.properties ├── extent-config.xml ├── README.md └── pom.xml /run.bat: -------------------------------------------------------------------------------- 1 | mvn clean test -Dvideo.enabled=false & allure generate allure-results -c -o allure-report && allure open allure-report -------------------------------------------------------------------------------- /src/test/resource/data/TestData.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VinayKumarBM/DataDrivenFramework-sample/HEAD/src/test/resource/data/TestData.xlsx -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/GlobalVariable.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | public class GlobalVariable { 4 | 5 | public static String basePath = System.getProperty("user.dir"); 6 | 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/DateUtility.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.text.SimpleDateFormat; 4 | import java.util.Date; 5 | 6 | public class DateUtility { 7 | 8 | public static String getStringDate(String dateFormat) { 9 | SimpleDateFormat dtf = new SimpleDateFormat(dateFormat); 10 | Date localDate = new Date(); 11 | return dtf.format(localDate).toString(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /testng.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.nar 17 | *.ear 18 | *.zip 19 | *.tar.gz 20 | *.rar 21 | 22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 23 | hs_err_pid* 24 | 25 | # Images files # 26 | *.png 27 | 28 | # other files and packages 29 | .classpath 30 | .project 31 | .settings/ 32 | target/ 33 | test-output/ 34 | allure-report/ 35 | allure-results/ 36 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/modules/HomePageModule.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.modules; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | 5 | import com.automationpractice.pageobjects.HomePageObject; 6 | 7 | import io.qameta.allure.Step; 8 | 9 | public class HomePageModule { 10 | 11 | private HomePageObject homePageObject; 12 | 13 | public HomePageModule(WebDriver driver) { 14 | homePageObject = new HomePageObject(driver); 15 | } 16 | 17 | @Step ("Navigate to Login Page") 18 | public void navigateToLoginPage() { 19 | homePageObject.clickOnSignInLink(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/listener/RetryFailedTestCases.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.listener; 2 | 3 | import org.testng.IRetryAnalyzer; 4 | import org.testng.ITestResult; 5 | 6 | public class RetryFailedTestCases implements IRetryAnalyzer { 7 | 8 | private int retryCount = 0; 9 | // If there are any failed test cases, then it runs 2 times 10 | private int maxRetryCount = 1; 11 | 12 | @Override 13 | public boolean retry(ITestResult arg0) { 14 | if(retryCount < maxRetryCount) { 15 | System.out.println("Retrying the failed test cases."); 16 | retryCount++; 17 | return true; 18 | } 19 | return false; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/modules/SearchPageModule.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.modules; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | 5 | import com.automationpractice.pageobjects.SearchPageObject; 6 | 7 | import io.qameta.allure.Step; 8 | 9 | public class SearchPageModule { 10 | 11 | private SearchPageObject searchPageObject; 12 | 13 | public SearchPageModule(WebDriver driver) { 14 | searchPageObject = new SearchPageObject(driver); 15 | } 16 | 17 | @Step ("Select a product: {0}") 18 | public boolean selectProduct(String product) { 19 | boolean found = searchPageObject.clickOnProduct(product); 20 | searchPageObject.clickProceedToCheckout(); 21 | return found; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/listener/RetryListener.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.listener; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.Method; 5 | 6 | import org.testng.IAnnotationTransformer; 7 | import org.testng.IRetryAnalyzer; 8 | import org.testng.annotations.ITestAnnotation; 9 | 10 | public class RetryListener implements IAnnotationTransformer { 11 | 12 | @Override 13 | public void transform(ITestAnnotation testannotation, Class testClass, Constructor testConstructor, Method testMethod) { 14 | IRetryAnalyzer retry = testannotation.getRetryAnalyzer(); 15 | if (retry == null) { 16 | testannotation.setRetryAnalyzer(RetryFailedTestCases.class); 17 | } 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /config.properties: -------------------------------------------------------------------------------- 1 | appUrl = http://automationpractice.com/index.php 2 | browser = Chrome 3 | webDriverWaitTime = 20 4 | implicitlyWaitTime = 5 5 | testCasePass = _PASS 6 | testCaseFail = _FAIL 7 | testCaseSkipped = _SKIPPED 8 | 9 | reportPath = /test-output/report/ 10 | screenShotFolderPath = /src/test/resource/screenshots/ 11 | fileFormat = .png 12 | 13 | testDataPath = /src/test/resource/data/TestData.xlsx 14 | testDataSheetName = testCaseData 15 | 16 | testCaseColumn = testCaseName 17 | firstNameColumn = firstName 18 | lastNameColumn = lastName 19 | passwordColumn = password 20 | emailIDColumn = emailID 21 | mobilePhoneColumn = mobilePhone 22 | addressColumn = address 23 | aliasAddressColumn = aliasAddress 24 | cityColumn = city 25 | countryColumn = country 26 | stateColumn = state 27 | zipCodeColumn = zipCode 28 | searchKeyColumn = searchKey 29 | productColumn = product -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/modules/OrderPageModule.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.modules; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | 5 | import com.automationpractice.pageobjects.OrderPageObject; 6 | 7 | import io.qameta.allure.Step; 8 | 9 | public class OrderPageModule { 10 | 11 | private OrderPageObject orderPageObject; 12 | 13 | public OrderPageModule(WebDriver driver) { 14 | orderPageObject = new OrderPageObject(driver); 15 | } 16 | 17 | @Step ("Placing the order") 18 | public String confirmOrder() { 19 | orderPageObject.clickSummaryProceedToCheckout(); 20 | orderPageObject.clickAddressProceedToCheckout(); 21 | orderPageObject.agreeToTerms(); 22 | orderPageObject.clickCarrierProceedToCheckout(); 23 | orderPageObject.clickPayByCheque(); 24 | orderPageObject.clickOnConfirmOrder(); 25 | return orderPageObject.orderConfirmationMsg(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/ConfigReader.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.io.InputStream; 6 | import java.util.Properties; 7 | 8 | public class ConfigReader { 9 | 10 | public final static String configFilePath= System.getProperty("user.dir")+"/config.properties"; 11 | 12 | public static String getProperty(String configKey) { 13 | 14 | Properties prop = new Properties(); 15 | InputStream input = null; 16 | String configValue = null; 17 | try { 18 | input = new FileInputStream(configFilePath); 19 | // load a properties file 20 | prop.load(input); 21 | configValue = prop.getProperty(configKey); 22 | } catch (IOException ex) { 23 | ex.printStackTrace(); 24 | } finally { 25 | try { 26 | input.close(); 27 | } catch (IOException e) { 28 | e.printStackTrace(); 29 | } 30 | } 31 | return configValue; 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /src/main/resources/log4j2.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/modules/MyAccountPageModule.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.modules; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | 5 | import com.automationpractice.pageobjects.MyAccountPageObject; 6 | 7 | import io.qameta.allure.Step; 8 | 9 | public class MyAccountPageModule { 10 | 11 | private MyAccountPageObject myAccountPageObject; 12 | 13 | public MyAccountPageModule(WebDriver driver) { 14 | myAccountPageObject = new MyAccountPageObject(driver); 15 | } 16 | 17 | @Step ("Navigate to My Account screen") 18 | public String userNavigatedToMyAccount() { 19 | return myAccountPageObject.validatesUserIsInMyAccountsPage(); 20 | } 21 | 22 | @Step ("Log out of My Store application") 23 | public void logOutOfApplication() { 24 | myAccountPageObject.logOut(); 25 | } 26 | 27 | @Step ("Search for product: {0}") 28 | public void searchForProduct(String searchKey) { 29 | myAccountPageObject.enterSearchKey(searchKey); 30 | myAccountPageObject.submitSearch(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/modules/LoginPageModule.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.modules; 2 | 3 | import java.util.Map; 4 | 5 | import org.openqa.selenium.WebDriver; 6 | 7 | import com.automationpractice.pageobjects.LoginPageObject; 8 | import com.automationpractice.utility.ConfigReader; 9 | import com.automationpractice.utility.DateUtility; 10 | 11 | import io.qameta.allure.Step; 12 | 13 | public class LoginPageModule { 14 | 15 | private LoginPageObject loginPageObject; 16 | 17 | public LoginPageModule(WebDriver driver) { 18 | loginPageObject = new LoginPageObject(driver); 19 | } 20 | 21 | @Step ("Enter email address to Create Account") 22 | public String enterEmailAddressToCreateAccount() { 23 | String email = String.format("test%s@gmail.com", DateUtility.getStringDate("DDhhmmss")); 24 | loginPageObject.enterEmailToCreateAccount(email); 25 | loginPageObject.clickOnCreateAccountButton(); 26 | return email; 27 | } 28 | 29 | @Step ("Login to My Store") 30 | public void loginToMyStore(Map testDataMap) { 31 | loginPageObject.enterEmailToSignin(testDataMap.get(ConfigReader.getProperty("emailIDColumn"))); 32 | loginPageObject.enterPassword(testDataMap.get(ConfigReader.getProperty("passwordColumn"))); 33 | loginPageObject.clickOnLoginButton(); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /extent-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | dark 7 | 8 | 9 | 10 | UTF-8 11 | 12 | 13 | 14 | https 15 | 16 | 17 | Automation Test Report 18 | 19 | 20 | My Store Test Results 21 | 22 | 23 | My Store Automation Report 24 | 25 | 26 | 27 | yyyy-MM-dd 28 | 29 | 30 | 31 | HH:mm:ss 32 | 33 | 34 | 35 | 40 | 41 | 42 | 43 | 44 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/pageobjects/MyAccountPageObject.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.pageobjects; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | import org.openqa.selenium.WebElement; 5 | import org.openqa.selenium.support.FindBy; 6 | import org.openqa.selenium.support.PageFactory; 7 | import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; 8 | 9 | import com.automationpractice.utility.ConfigReader; 10 | 11 | public class MyAccountPageObject { 12 | 13 | public MyAccountPageObject(WebDriver driver) { 14 | PageFactory.initElements(new AjaxElementLocatorFactory(driver, 15 | Integer.parseInt(ConfigReader.getProperty("webDriverWaitTime"))), this); 16 | } 17 | 18 | @FindBy(css = ".page-heading") 19 | private WebElement pageHeading; 20 | 21 | @FindBy(linkText = "Sign out") 22 | private WebElement signOut; 23 | 24 | @FindBy(name = "search_query") 25 | private WebElement searchQuery; 26 | 27 | @FindBy(name = "submit_search") 28 | private WebElement submitSearch; 29 | 30 | public String validatesUserIsInMyAccountsPage() { 31 | return pageHeading.getText().trim(); 32 | } 33 | 34 | public void logOut() { 35 | signOut.click(); 36 | } 37 | 38 | public void enterSearchKey(String searchKey) { 39 | searchQuery.clear(); 40 | searchQuery.sendKeys(searchKey); 41 | } 42 | 43 | public void submitSearch() { 44 | submitSearch.click(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/ResourceUtility.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class ResourceUtility { 9 | 10 | public static String getScreenShotFolderPath() { 11 | String screenShotFolderPath = GlobalVariable.basePath +ConfigReader.getProperty("screenShotFolderPath"); 12 | createDirectory(screenShotFolderPath); 13 | return screenShotFolderPath; 14 | } 15 | 16 | public static String getReportFolderPath() { 17 | String reportFolderPath = GlobalVariable.basePath +ConfigReader.getProperty("reportPath"); 18 | createDirectory(reportFolderPath); 19 | return reportFolderPath; 20 | } 21 | 22 | public static String getDataFolderPath() { 23 | return GlobalVariable.basePath+ConfigReader.getProperty("testDataPath"); 24 | } 25 | 26 | private static boolean createDirectory(String folderPath) { 27 | Path path = Paths.get(folderPath); 28 | //if directory exists? 29 | if (!Files.exists(path)) { 30 | try { 31 | Files.createDirectories(path); 32 | System.out.println("Directory was created.\n"+folderPath); 33 | return true; 34 | } catch (IOException exp) { 35 | System.out.println(exp.getMessage()+"\n"+exp); 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/ReportManager.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.io.File; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import com.aventstack.extentreports.ExtentReports; 8 | import com.aventstack.extentreports.ExtentTest; 9 | import com.aventstack.extentreports.reporter.ExtentHtmlReporter; 10 | 11 | public class ReportManager { 12 | private static ExtentReports extent; 13 | static Map extentTestMap = new HashMap(); 14 | private static String basePath = GlobalVariable.basePath; 15 | private static String extentConfigFilePath = basePath+"/extent-config.xml"; 16 | 17 | //Create an extent report instance 18 | private static ExtentReports createInstance() { 19 | String fileName = ResourceUtility.getReportFolderPath()+"test-report.html"; 20 | ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(fileName); 21 | htmlReporter.loadXMLConfig(new File(extentConfigFilePath)); 22 | extent = new ExtentReports(); 23 | extent.attachReporter(htmlReporter); 24 | return extent; 25 | } 26 | 27 | static ExtentReports getInstance() { 28 | if (extent == null) { 29 | createInstance(); 30 | } 31 | return extent; 32 | } 33 | 34 | public static synchronized ExtentTest getTest() { 35 | return (ExtentTest) extentTestMap.get((int) (long) (Thread.currentThread().getId())); 36 | } 37 | 38 | public static synchronized void endTest() { 39 | getInstance().flush(); 40 | } 41 | 42 | public static synchronized ExtentTest startTest(String testName) { 43 | ExtentTest test = getInstance().createTest(testName); 44 | extentTestMap.put((int) (long) (Thread.currentThread().getId()), test); 45 | return test; 46 | } 47 | 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/pageobjects/LoginPageObject.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.pageobjects; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | import org.openqa.selenium.WebElement; 5 | import org.openqa.selenium.support.FindBy; 6 | import org.openqa.selenium.support.PageFactory; 7 | import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; 8 | 9 | import com.automationpractice.utility.ConfigReader; 10 | import com.automationpractice.utility.Log; 11 | 12 | public class LoginPageObject { 13 | 14 | public LoginPageObject(WebDriver driver) { 15 | PageFactory.initElements(new AjaxElementLocatorFactory(driver, 16 | Integer.parseInt(ConfigReader.getProperty("webDriverWaitTime"))), this); 17 | } 18 | 19 | @FindBy(name = "email_create") 20 | private WebElement createAccountEmail; 21 | 22 | @FindBy(name ="SubmitCreate") 23 | private WebElement createAccount_Button; 24 | 25 | @FindBy(name ="email") 26 | private WebElement registeredEmail; 27 | 28 | @FindBy(name ="passwd") 29 | private WebElement password; 30 | 31 | @FindBy(xpath ="//button[@name='SubmitLogin']") 32 | private WebElement login_Button; 33 | 34 | public void enterEmailToCreateAccount(String email) { 35 | Log.info("Entering from Login Page"); 36 | createAccountEmail.sendKeys(email); 37 | } 38 | 39 | public void clickOnCreateAccountButton() { 40 | createAccount_Button.click(); 41 | } 42 | 43 | public void enterEmailToSignin(String email) { 44 | registeredEmail.clear(); 45 | registeredEmail.sendKeys(email); 46 | } 47 | 48 | public void enterPassword(String password) { 49 | this.password.clear(); 50 | this.password.sendKeys(password); 51 | } 52 | 53 | public void clickOnLoginButton() { 54 | login_Button.click(); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/modules/CreateAccountPageModule.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.modules; 2 | 3 | import java.util.Map; 4 | 5 | import org.openqa.selenium.WebDriver; 6 | 7 | import com.automationpractice.pageobjects.CreateAccountPageObject; 8 | import com.automationpractice.utility.ConfigReader; 9 | 10 | import io.qameta.allure.Step; 11 | 12 | public class CreateAccountPageModule { 13 | private CreateAccountPageObject createAccountPageObject; 14 | 15 | public CreateAccountPageModule(WebDriver driver) { 16 | createAccountPageObject = new CreateAccountPageObject(driver); 17 | } 18 | 19 | @Step ("Entering the Account details") 20 | public void createAccount(Map testDataMap) { 21 | createAccountPageObject.enterFirstName(testDataMap.get(ConfigReader.getProperty("firstNameColumn"))); 22 | createAccountPageObject.enterLastName(testDataMap.get(ConfigReader.getProperty("lastNameColumn"))); 23 | createAccountPageObject.enterPassword(testDataMap.get(ConfigReader.getProperty("passwordColumn"))); 24 | createAccountPageObject.enterAddress(testDataMap.get(ConfigReader.getProperty("addressColumn"))); 25 | createAccountPageObject.enterCity(testDataMap.get(ConfigReader.getProperty("cityColumn"))); 26 | createAccountPageObject.selectCountry(testDataMap.get(ConfigReader.getProperty("countryColumn"))); 27 | createAccountPageObject.selectState(testDataMap.get(ConfigReader.getProperty("stateColumn"))); 28 | createAccountPageObject.enterZipCode(testDataMap.get(ConfigReader.getProperty("zipCodeColumn"))); 29 | createAccountPageObject.enterMobilePhone(testDataMap.get(ConfigReader.getProperty("mobilePhoneColumn"))); 30 | createAccountPageObject.enterAliasAddress(testDataMap.get(ConfigReader.getProperty("aliasAddressColumn"))); 31 | createAccountPageObject.clickOnRegisterButton(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/listener/Listener.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.listener; 2 | 3 | import org.testng.ITestContext; 4 | import org.testng.ITestListener; 5 | import org.testng.ITestResult; 6 | 7 | import com.automationpractice.utility.ConfigReader; 8 | import com.automationpractice.utility.Log; 9 | import com.automationpractice.utility.ReportManager; 10 | import com.aventstack.extentreports.Status; 11 | 12 | public class Listener implements ITestListener{ 13 | 14 | @Override 15 | public void onFinish(ITestContext result) { 16 | ReportManager.endTest(); 17 | } 18 | 19 | @Override 20 | public void onStart(ITestContext result) { 21 | 22 | } 23 | 24 | @Override 25 | public void onTestFailedButWithinSuccessPercentage(ITestResult result) { 26 | 27 | } 28 | 29 | @Override 30 | public void onTestFailure(ITestResult result) { 31 | String testCaseName = result.getName(); 32 | String status = testCaseName+ConfigReader.getProperty("testCaseFail"); 33 | Log.error(status); 34 | Log.endTestCase(testCaseName, "FAILED"); 35 | ReportManager.getTest().log(Status.FAIL, status+"\n"+result.getThrowable()); 36 | } 37 | 38 | @Override 39 | public void onTestSkipped(ITestResult result) { 40 | String testCaseName = result.getName(); 41 | String status = testCaseName+ConfigReader.getProperty("testCaseSkipped"); 42 | Log.info(status); 43 | ReportManager.getTest().log(Status.SKIP, status); 44 | } 45 | 46 | @Override 47 | public void onTestStart(ITestResult result) { 48 | ReportManager.startTest(result.getName()); 49 | Log.startTestCase(result.getName()); 50 | } 51 | 52 | @Override 53 | public void onTestSuccess(ITestResult result) { 54 | String testCaseName = result.getName(); 55 | String status = testCaseName+ConfigReader.getProperty("testCasePass"); 56 | Log.endTestCase(testCaseName, "PASSED"); 57 | ReportManager.getTest().log(Status.PASS, status); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/ScreenshotUtility.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | import javax.imageio.ImageIO; 7 | 8 | import org.apache.commons.io.FileUtils; 9 | import org.openqa.selenium.OutputType; 10 | import org.openqa.selenium.TakesScreenshot; 11 | import org.openqa.selenium.WebDriver; 12 | 13 | import ru.yandex.qatools.ashot.AShot; 14 | import ru.yandex.qatools.ashot.Screenshot; 15 | import ru.yandex.qatools.ashot.shooting.ShootingStrategies; 16 | 17 | public class ScreenshotUtility { 18 | 19 | public static String takeScreenShot(WebDriver driver,String testCaseName){ 20 | // Take screenshot and store as a file format 21 | File src= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); 22 | String screenShotFilePath = ResourceUtility.getScreenShotFolderPath()+testCaseName+DateUtility.getStringDate("_ddMMyyyy_HHmmss") 23 | +ConfigReader.getProperty("fileFormat"); 24 | try{ 25 | FileUtils.copyFile(src, new File(screenShotFilePath)); 26 | } 27 | catch(Exception exp){ 28 | Log.error("Exception occured in takeScreenShot: "+exp.getMessage()); 29 | } 30 | return screenShotFilePath; 31 | } 32 | 33 | public static String takeFullScreenShot(WebDriver driver,String testCaseName){ 34 | // Take full screenshot and store as a file format 35 | String screenShotFilePath = ResourceUtility.getScreenShotFolderPath()+testCaseName+DateUtility.getStringDate("_ddMMyyyy_HHmmss") 36 | +ConfigReader.getProperty("fileFormat"); 37 | Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver); 38 | try { 39 | ImageIO.write(screenshot.getImage(),"PNG",new File(screenShotFilePath)); 40 | } catch (IOException exp) { 41 | Log.error("Exception occured in takeScreenShot: "+exp.getMessage()); 42 | } 43 | return screenShotFilePath; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/pageobjects/SearchPageObject.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.pageobjects; 2 | 3 | import java.util.List; 4 | 5 | import org.openqa.selenium.By; 6 | import org.openqa.selenium.WebDriver; 7 | import org.openqa.selenium.WebElement; 8 | import org.openqa.selenium.interactions.Actions; 9 | import org.openqa.selenium.support.FindBy; 10 | import org.openqa.selenium.support.PageFactory; 11 | import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; 12 | 13 | import com.automationpractice.utility.ConfigReader; 14 | import com.automationpractice.utility.Log; 15 | 16 | public class SearchPageObject { 17 | private WebDriver driver; 18 | 19 | public SearchPageObject(WebDriver driver) { 20 | this.driver = driver; 21 | PageFactory.initElements(new AjaxElementLocatorFactory(driver, 22 | Integer.parseInt(ConfigReader.getProperty("webDriverWaitTime"))), this); 23 | } 24 | 25 | @FindBy(xpath = "//a[@class='product_img_link']") 26 | private List productList; 27 | 28 | @FindBy(xpath = "//a[@title='Proceed to checkout']/span") 29 | private WebElement proceedToCheckout; 30 | 31 | private String addToCartButtonXpath = "//a[@title='%s']/../../div/a/span[text()='Add to cart']"; 32 | 33 | public boolean clickOnProduct(String product) { 34 | for(int i=0; i testDataMap = new ExcelUtility().getData(testCaseName, excelSheetPath, 37 | ConfigReader.getProperty("testDataSheetName")); 38 | 39 | homePageModule.navigateToLoginPage(); 40 | test.log(Status.INFO, "Navigated to login page."); 41 | loginPageModule.loginToMyStore(testDataMap); 42 | String pageHeading = myAccountPageModule.userNavigatedToMyAccount(); 43 | Log.info("User is in "+pageHeading+" page"); 44 | Assert.assertEquals(pageHeading, "MY ACCOUNT", "Page Heading did not match "); 45 | test.log(Status.INFO, "Logged into the Application."); 46 | } catch(Exception exp) { 47 | Log.error(exp.getMessage(), exp); 48 | test.error("Exception Occured: "+Thread.currentThread().getStackTrace()); 49 | Assert.fail(testCaseName); 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/DriverManager.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | import org.openqa.selenium.support.events.EventFiringWebDriver; 5 | 6 | import com.automationpractice.listener.WebDriverListener; 7 | 8 | public class DriverManager { 9 | 10 | private static DriverManager driverManager; 11 | private static ThreadLocal tDriver = new ThreadLocal<>(); 12 | private static ThreadLocal tEventFiringWebDriver = new ThreadLocal<>(); 13 | private static ThreadLocal tWebDriverListener = new ThreadLocal<>(); 14 | 15 | private DriverManager() { 16 | 17 | } 18 | 19 | public static DriverManager getInstance(){ 20 | if(driverManager == null) { 21 | synchronized (DriverManager.class) { 22 | driverManager = new DriverManager(); 23 | } 24 | } 25 | return driverManager; 26 | } 27 | 28 | public synchronized void setDriver (WebDriver driver) { 29 | tDriver.set(driver); 30 | } 31 | 32 | public synchronized WebDriver getDriver () { 33 | WebDriver driver = tDriver.get(); 34 | if (driver == null) { 35 | throw new IllegalStateException("Driver should have not been null!!"); 36 | } 37 | return driver; 38 | } 39 | 40 | public synchronized void setWebDriverListener (WebDriverListener listener) { 41 | tWebDriverListener.set(listener); 42 | } 43 | 44 | public synchronized WebDriverListener getWebDriverListener () { 45 | WebDriverListener listener = tWebDriverListener.get(); 46 | if (listener == null) { 47 | throw new IllegalStateException("WebDriverListener should have not been null!!"); 48 | } 49 | return listener; 50 | } 51 | 52 | public synchronized void setEventFiringWebDriver (EventFiringWebDriver eventFiringWebDriver) { 53 | tEventFiringWebDriver.set(eventFiringWebDriver); 54 | } 55 | 56 | public synchronized EventFiringWebDriver getEventFiringWebDriver () { 57 | EventFiringWebDriver eventFiringWebDriver = tEventFiringWebDriver.get(); 58 | if (eventFiringWebDriver == null) { 59 | throw new IllegalStateException("EventFiringWebDriver should have not been null!!"); 60 | } 61 | return eventFiringWebDriver; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/pageobjects/OrderPageObject.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.pageobjects; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | import org.openqa.selenium.WebElement; 5 | import org.openqa.selenium.support.FindBy; 6 | import org.openqa.selenium.support.PageFactory; 7 | import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; 8 | 9 | import com.automationpractice.utility.ConfigReader; 10 | import com.automationpractice.utility.Log; 11 | 12 | public class OrderPageObject { 13 | 14 | public OrderPageObject(WebDriver driver) { 15 | PageFactory.initElements(new AjaxElementLocatorFactory(driver, 16 | Integer.parseInt(ConfigReader.getProperty("webDriverWaitTime"))), this); 17 | } 18 | 19 | @FindBy(xpath = "//div[@id='center_column']//a[@title='Proceed to checkout']/span") 20 | private WebElement proceedToCheckoutSummary; 21 | 22 | @FindBy(name = "processAddress") 23 | private WebElement proceedToCheckoutAddress; 24 | 25 | @FindBy(id = "cgv") 26 | private WebElement agreeTerms; 27 | 28 | @FindBy(name = "processCarrier") 29 | private WebElement proceedToCheckoutCarrier; 30 | 31 | @FindBy(xpath = "//a[@class='cheque']") 32 | private WebElement payByCheck; 33 | 34 | @FindBy(xpath = "//span[text()='I confirm my order']") 35 | private WebElement confirmOrder; 36 | 37 | @FindBy(xpath = "//p[@class='alert alert-success']") 38 | private WebElement orderConfirmMsg; 39 | 40 | public void clickSummaryProceedToCheckout() { 41 | Log.info("Clicking on Summary Proceed to checkout"); 42 | proceedToCheckoutSummary.click(); 43 | } 44 | 45 | public void clickAddressProceedToCheckout() { 46 | Log.info("Clicking on Address Proceed to checkout"); 47 | proceedToCheckoutAddress.click(); 48 | } 49 | 50 | public void agreeToTerms() { 51 | Log.info("Agreeing to Terms of Service"); 52 | agreeTerms.click(); 53 | } 54 | 55 | public void clickCarrierProceedToCheckout() { 56 | Log.info("Clicking on Carrier Proceed to checkout"); 57 | proceedToCheckoutCarrier.click(); 58 | } 59 | 60 | public void clickPayByCheque() { 61 | Log.info("Clicking on Pay By Cheque"); 62 | payByCheck.click(); 63 | } 64 | 65 | public void clickOnConfirmOrder() { 66 | Log.info("Clicking on I confirm Order"); 67 | confirmOrder.click(); 68 | } 69 | 70 | public String orderConfirmationMsg() { 71 | return orderConfirmMsg.getText(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/pageobjects/HomePageObject.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.pageobjects; 2 | 3 | import java.util.List; 4 | 5 | import org.openqa.selenium.By; 6 | import org.openqa.selenium.WebDriver; 7 | import org.openqa.selenium.WebElement; 8 | import org.openqa.selenium.support.FindBy; 9 | import org.openqa.selenium.support.PageFactory; 10 | import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; 11 | 12 | import com.automationpractice.utility.ConfigReader; 13 | import com.automationpractice.utility.Log; 14 | 15 | public class HomePageObject { 16 | 17 | public HomePageObject(WebDriver driver) { 18 | PageFactory.initElements(new AjaxElementLocatorFactory(driver, 19 | Integer.parseInt(ConfigReader.getProperty("webDriverWaitTime"))), this); 20 | } 21 | 22 | @FindBy(name = "search_query") 23 | private WebElement searchBox; 24 | 25 | @FindBy(name = "submit_search") 26 | private WebElement searchButton; 27 | 28 | @FindBy(xpath = "//div[@class='right-block']/h5/a[@class='product-name']") 29 | List productList; 30 | 31 | @FindBy(xpath = "//span[@class='cat-name']") 32 | private WebElement subCategory; 33 | 34 | @FindBy(partialLinkText = "Sign in") 35 | private WebElement signIn_Link; 36 | 37 | public void productSearch(String searchKey) { 38 | searchBox.clear(); 39 | searchBox.sendKeys(searchKey); 40 | searchButton.click(); 41 | } 42 | 43 | public boolean productMatches(String searchKey) { 44 | int productCount = productList.size(); 45 | System.out.println("Number of Product Listed: "+productCount); 46 | String product = null; 47 | for(int i=0; i testDataMap = new ExcelUtility().getData(testCaseName, excelSheetPath, 40 | ConfigReader.getProperty("testDataSheetName")); 41 | 42 | homePageModule.navigateToLoginPage(); 43 | test.log(Status.INFO, "Navigated to login page."); 44 | String email = loginPageModule.enterEmailAddressToCreateAccount(); 45 | Log.info("Account will be created with email ID: "+email); 46 | test.log(Status.INFO, "Account will be created with email ID: "+email); 47 | createAccountPageModule.createAccount(testDataMap); 48 | String pageHeading = myAccountPageModule.userNavigatedToMyAccount(); 49 | Log.info("User is in "+pageHeading+" page"); 50 | Assert.assertEquals(pageHeading, "MY ACCOUNT", "Page Heading did not match "); 51 | test.log(Status.INFO, "Account was created."); 52 | myAccountPageModule.logOutOfApplication(); 53 | test.log(Status.INFO, "Logged out of Application"); 54 | } catch(Exception exp) { 55 | Log.error(exp.getMessage(), exp); 56 | Assert.fail(testCaseName); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/AllureConfigurator.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.FileWriter; 7 | import java.io.IOException; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Properties; 11 | 12 | import org.apache.commons.io.FileUtils; 13 | import org.openqa.selenium.json.Json; 14 | 15 | public class AllureConfigurator { 16 | 17 | private static File resultsDirectory = new File("allure-results"); 18 | private static File reportHistoryDirectory = new File("allure-report"+File.separator+"history"); 19 | private static File resultsHistoryDirectory = new File("allure-results"+File.separator+"history"); 20 | private static final String PATH = resultsDirectory.getAbsolutePath()+File.separator+"%s"; 21 | 22 | public static void configure() throws IOException{ 23 | makeCopyOfHistory(); 24 | createEnvironmentFile(); 25 | createExecutorJSON(); 26 | } 27 | 28 | private static void createEnvironmentFile() throws FileNotFoundException, IOException { 29 | Properties props = new Properties(); 30 | props.put("User", System.getProperty("user.name")); 31 | props.put("Browser", ConfigReader.getProperty("browser")); 32 | props.put("URL", ConfigReader.getProperty("appUrl")); 33 | props.put("OS", System.getProperty("os.name")); 34 | 35 | FileOutputStream outputStrem = new FileOutputStream(String.format(PATH, "environment.properties")); 36 | props.store(outputStrem, "This is a properties file for Allure environment details"); 37 | System.out.println("Environment Properties file created"); 38 | } 39 | 40 | private static void makeCopyOfHistory() throws IOException { 41 | if(!resultsDirectory.exists()) { 42 | System.out.println("Creating new Report Directory"); 43 | resultsDirectory.mkdir(); 44 | } 45 | 46 | if(reportHistoryDirectory.exists()) { 47 | resultsHistoryDirectory.mkdir(); 48 | FileUtils.copyDirectory(new File(reportHistoryDirectory.getAbsolutePath()), 49 | new File(resultsHistoryDirectory.getAbsolutePath())); 50 | System.out.println("Copied history to results directory!"); 51 | } 52 | } 53 | 54 | private static void createExecutorJSON() throws IOException { 55 | Map executorMap = new HashMap(); 56 | executorMap.put("name", System.getProperty("user.name")); 57 | executorMap.put("buildName", System.getProperty("os.name")); 58 | executorMap.put("type", "jenkins"); 59 | 60 | FileWriter file = new FileWriter(String.format(PATH, "executor.json")); 61 | file.write(new Json().toJson(executorMap)); 62 | file.flush(); 63 | System.out.println("Executor JSON file created"); 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/pageobjects/CreateAccountPageObject.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.pageobjects; 2 | 3 | import org.openqa.selenium.WebDriver; 4 | import org.openqa.selenium.WebElement; 5 | import org.openqa.selenium.support.FindBy; 6 | import org.openqa.selenium.support.PageFactory; 7 | import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory; 8 | import org.openqa.selenium.support.ui.Select; 9 | 10 | import com.automationpractice.utility.ConfigReader; 11 | 12 | public class CreateAccountPageObject { 13 | 14 | public CreateAccountPageObject(WebDriver driver) { 15 | PageFactory.initElements(new AjaxElementLocatorFactory(driver, 16 | Integer.parseInt(ConfigReader.getProperty("webDriverWaitTime"))), this); 17 | } 18 | 19 | @FindBy(id = "id_gender1") 20 | private WebElement title; 21 | 22 | @FindBy(id = "customer_firstname") 23 | private WebElement firstName; 24 | 25 | @FindBy(id = "customer_lastname") 26 | private WebElement lastName; 27 | 28 | @FindBy(id = "passwd") 29 | private WebElement password; 30 | 31 | @FindBy(id = "address1") 32 | private WebElement address; 33 | 34 | @FindBy(id = "city") 35 | private WebElement city; 36 | 37 | @FindBy(id = "id_state") 38 | private WebElement state; 39 | 40 | @FindBy(id = "postcode") 41 | private WebElement zipCode; 42 | 43 | @FindBy(id = "id_country") 44 | private WebElement country; 45 | 46 | @FindBy(id = "phone_mobile") 47 | private WebElement mobilePhone; 48 | 49 | @FindBy(id = "alias") 50 | private WebElement aliasAddress; 51 | 52 | @FindBy(id = "submitAccount") 53 | private WebElement register_button; 54 | 55 | public void enterFirstName(String firstName) { 56 | this.firstName.sendKeys(firstName); 57 | } 58 | 59 | public void enterLastName(String lastName) { 60 | this.lastName.sendKeys(lastName); 61 | } 62 | 63 | public void enterPassword(String password) { 64 | this.password.sendKeys(password); 65 | } 66 | 67 | public void enterAddress(String address) { 68 | this.address.clear(); 69 | this.address.sendKeys(address); 70 | } 71 | 72 | public void selectCountry(String country) { 73 | new Select(this.country).selectByVisibleText(country); 74 | } 75 | 76 | public void selectState(String state) { 77 | new Select(this.state).selectByVisibleText(state); 78 | } 79 | 80 | public void enterZipCode(String zipCode) { 81 | this.zipCode.sendKeys(zipCode); 82 | } 83 | 84 | public void enterCity(String city) { 85 | this.city.sendKeys(city); 86 | } 87 | 88 | public void enterMobilePhone(String mobilePhone) { 89 | this.mobilePhone.sendKeys(mobilePhone); 90 | } 91 | 92 | public void enterAliasAddress(String aliasAddress) { 93 | this.aliasAddress.clear(); 94 | this.aliasAddress.sendKeys(aliasAddress); 95 | } 96 | 97 | public void clickOnRegisterButton() { 98 | this.register_button.click(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/test/java/com/automationpractice/runner/TestRunner.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.runner; 2 | 3 | import org.testng.annotations.Listeners; 4 | import org.testng.annotations.Test; 5 | 6 | import com.automation.remarks.testng.UniversalVideoListener; 7 | import com.automation.remarks.video.annotations.Video; 8 | import com.automationpractice.listener.Listener; 9 | import com.automationpractice.scripts.CreateAccountScript; 10 | import com.automationpractice.scripts.LoginScript; 11 | import com.automationpractice.scripts.ProductCheckoutScript; 12 | import com.automationpractice.utility.DriverManager; 13 | 14 | import io.qameta.allure.Description; 15 | import io.qameta.allure.Epic; 16 | import io.qameta.allure.Feature; 17 | import io.qameta.allure.Severity; 18 | import io.qameta.allure.SeverityLevel; 19 | import io.qameta.allure.Story; 20 | 21 | @Listeners ({Listener.class, UniversalVideoListener.class}) 22 | @Epic ("My Store Epic") 23 | @Feature ("To test the functionality of My Store application") 24 | public class TestRunner extends TestBase{ 25 | 26 | @Video 27 | @Test (groups = { "regression"}) 28 | @Severity (SeverityLevel.NORMAL) 29 | @Description ("Test to verify the creation of new account") 30 | @Story ("Create Account") 31 | public void TC001_CreateNewAccount() { 32 | String testCaseName = new Object(){}.getClass().getEnclosingMethod().getName(); 33 | CreateAccountScript createAccountScript = new CreateAccountScript(DriverManager.getInstance().getDriver()); 34 | createAccountScript.createAnAccount(testCaseName); 35 | } 36 | 37 | @Video 38 | @Test (groups = { "regression","smoke"}) 39 | @Severity (SeverityLevel.NORMAL) 40 | @Description ("Test to verify the purchase the Printed Summary Dress") 41 | @Story ("Purchase Dress") 42 | public void TC002_PurchasePrintedSummaryDress() { 43 | String testCaseName = new Object(){}.getClass().getEnclosingMethod().getName(); 44 | ProductCheckoutScript productCheckoutScript = new ProductCheckoutScript(DriverManager.getInstance().getDriver()); 45 | productCheckoutScript.checkOutProduct(testCaseName); 46 | } 47 | 48 | @Video 49 | @Test (groups = { "regression"}) 50 | @Severity (SeverityLevel.NORMAL) 51 | @Description ("Test to verify the purchase the Printed Chiffon Dress") 52 | @Story ("Purchase Dress") 53 | public void TC003_PurchasePrintedChiffonDress() { 54 | String testCaseName = new Object(){}.getClass().getEnclosingMethod().getName(); 55 | ProductCheckoutScript productCheckoutScript = new ProductCheckoutScript(DriverManager.getInstance().getDriver()); 56 | productCheckoutScript.checkOutProduct(testCaseName); 57 | } 58 | 59 | @Video 60 | @Test 61 | @Severity (SeverityLevel.NORMAL) 62 | @Description ("Test to verify the login functionality with invalid credentials") 63 | @Story ("Login to Application") 64 | public void TC004_InvalidLogin() { 65 | String testCaseName = new Object(){}.getClass().getEnclosingMethod().getName(); 66 | LoginScript loginScript = new LoginScript(DriverManager.getInstance().getDriver()); 67 | loginScript.loginTest(testCaseName); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/scripts/ProductCheckoutScript.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.scripts; 2 | 3 | import java.util.Map; 4 | 5 | import org.openqa.selenium.WebDriver; 6 | import org.testng.Assert; 7 | 8 | import com.automationpractice.modules.HomePageModule; 9 | import com.automationpractice.modules.LoginPageModule; 10 | import com.automationpractice.modules.MyAccountPageModule; 11 | import com.automationpractice.modules.OrderPageModule; 12 | import com.automationpractice.modules.SearchPageModule; 13 | import com.automationpractice.utility.ConfigReader; 14 | import com.automationpractice.utility.ExcelUtility; 15 | import com.automationpractice.utility.Log; 16 | import com.automationpractice.utility.ReportManager; 17 | import com.automationpractice.utility.ResourceUtility; 18 | import com.aventstack.extentreports.ExtentTest; 19 | import com.aventstack.extentreports.Status; 20 | 21 | public class ProductCheckoutScript { 22 | private WebDriver driver; 23 | private HomePageModule homePageModule; 24 | private LoginPageModule loginPageModule; 25 | private SearchPageModule searchPageModule; 26 | private MyAccountPageModule myAccountPageModule; 27 | private OrderPageModule orderPageModule; 28 | private String excelSheetPath = ResourceUtility.getDataFolderPath(); 29 | 30 | public ProductCheckoutScript(WebDriver driver) { 31 | this.driver = driver; 32 | homePageModule = new HomePageModule(driver); 33 | loginPageModule = new LoginPageModule(driver); 34 | searchPageModule = new SearchPageModule(driver); 35 | myAccountPageModule = new MyAccountPageModule(driver); 36 | orderPageModule = new OrderPageModule(driver); 37 | } 38 | 39 | public void checkOutProduct(String testCaseName) { 40 | ExtentTest test = ReportManager.getTest(); 41 | try { 42 | Map testDataMap = new ExcelUtility().getData(testCaseName, excelSheetPath, 43 | ConfigReader.getProperty("testDataSheetName")); 44 | 45 | homePageModule.navigateToLoginPage(); 46 | test.log(Status.INFO, "Navigated to login page."); 47 | loginPageModule.loginToMyStore(testDataMap); 48 | test.log(Status.INFO, "Logged into the Application."); 49 | myAccountPageModule.searchForProduct(testDataMap.get(ConfigReader.getProperty("searchKeyColumn"))); 50 | test.log(Status.INFO, "Searching for product: "+ConfigReader.getProperty("searchKeyColumn")); 51 | boolean status = searchPageModule.selectProduct(testDataMap.get(ConfigReader.getProperty("productColumn"))); 52 | Assert.assertTrue(status, "Product was not found."); 53 | test.log(Status.INFO, "Added product to cart."); 54 | String orderConfirmMsg = orderPageModule.confirmOrder(); 55 | Assert.assertEquals(orderConfirmMsg, "Your order on My Store is complete.","Order was not confirmed"); 56 | test.log(Status.INFO, "Order on My Store is complete."); 57 | myAccountPageModule.logOutOfApplication(); 58 | test.log(Status.INFO, "Logged out of Application"); 59 | } catch(Exception exp) { 60 | Log.error(exp.getMessage(), exp); 61 | test.error("Exception Occured: "+Thread.currentThread().getStackTrace()); 62 | Assert.fail(testCaseName); 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DataDrivenFramework-sample 2 | 3 | ## **Overview:** 4 | 5 | Data Driven framework is focused on separating the test scripts logic and the test data from each other. This allows us to create test automation scripts by passing different sets of test data. The test data set is kept in the external files or resources such as MS Excel Sheets, MS Access Tables, SQL Database, XML files etc., The test scripts connect to the external resources to get the test data. This framework significantly reduces the number of test scripts compared to a modular based framework when we need to test for multiple sets of data for same functionality. 6 | 7 | For Demo purpose all the test cases are created for [automationpractice.com](http://automationpractice.com/index.php) site. 8 | 9 | ### **Some of the key features of this framework:** 10 | 11 | 1. It generates Extent & Allure reports with all the step details. 12 | 2. It support parallel execution of test cases. 13 | 3. It generates test execution log file. 14 | 4. Test execution can be triggered form command line. 15 | 5. Easy integration to CI/CD pipeline. 16 | 6. Framework uses Page Object Design Pattern, hence there is clean separation between test code and page specific code such as locators and layout. 17 | 7. Framework has the capability to re-run the failed test cases. 18 | 8. Video recording of test execution can be enabled in local test runs 19 | 20 | ## **Required Setup :** 21 | 22 | - [Java](https://www.guru99.com/install-java.html) should be installed and configured. 23 | - [Maven](https://mkyong.com/maven/how-to-install-maven-in-windows/) should be installed and configured. 24 | - Download the files from Git repository either as zip file OR using [Git](https://phoenixnap.com/kb/how-to-install-git-windows). 25 | - Download and install [Allure](https://github.com/allure-framework/allure-docs/blob/master/docs/getstarted.adoc) commandline application, suitable for your environment. 26 | 27 | ## **Running Test:** 28 | 29 | Open the command prompt and navigate to the folder in which pom.xml file is present. 30 | Run the below Maven command. 31 | 32 | mvn clean test -Dvideo.enabled=false 33 | 34 | This will run 2 test cases in parallel (default thread count is 2) and video recording in disabled mode. 35 | Once the execution completes report will be generated in below folder structure. 36 | 37 | **Extent Report:** */test-output/report/test-report.html* 38 | 39 | **Allure Report:** To generate the report we need to go through below steps. 40 | 41 | To generate the report from existing Allure results use below command. 42 | 43 | allure generate allure-results -c -o allure-report 44 | 45 | After the report is generated, open it in default system browser using below command. 46 | 47 | allure open allure-report 48 | 49 | **Video Recoding:** 50 | 51 | To execute the test cases with [video recording](http://automation-remarks.com/video-recorder-java/) feature run below command. 52 | 53 | mvn clean test -Dvideo.enabled=true -Dparallel.thread=1 54 | 55 | ###### **Note:** 56 | 1. Video recording works well only on local and non parallel execution mode as the video recorder captures the screen. 57 | 2. As screen action is been captured by video recorder don't perform any action on screen while test is executing. 58 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/Log.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import org.apache.logging.log4j.LogManager; 4 | import org.apache.logging.log4j.Logger; 5 | import org.apache.logging.log4j.ThreadContext; 6 | 7 | public class Log { 8 | 9 | //Initialize Log4j logs 10 | private static Logger log = LogManager.getLogger(); 11 | 12 | // This is to print log for the beginning of the test case 13 | public static synchronized void startTestCase(String testCaseName){ 14 | testCaseName = testCaseName.replaceAll("[^a-zA-Z0-9]", "_").replaceAll("_+", "_"); 15 | ThreadContext.put("logFilename", testCaseName); 16 | info("*****************************************************************************************"); 17 | info(""); 18 | info("\t\t\t--{ "+testCaseName.toUpperCase()+" - STARTS }--"); 19 | info(""); 20 | info("*****************************************************************************************"); 21 | } 22 | 23 | //This is to print log for the ending of the test case 24 | public static void endTestCase(String testCaseName, String status){ 25 | info("*****************************************************************************************"); 26 | info(""); 27 | info("\t\t\t--{ "+testCaseName.toUpperCase()+" - "+status+" }--"); 28 | info(""); 29 | info("*****************************************************************************************"); 30 | } 31 | 32 | public static Logger getCurrentLog() { 33 | return log; 34 | } 35 | 36 | public static String getCallInfo() { 37 | String callInfo; 38 | String className = Thread.currentThread().getStackTrace()[3].getClassName(); 39 | String methodName = Thread.currentThread().getStackTrace()[3].getMethodName(); 40 | int lineNumber = Thread.currentThread().getStackTrace()[3].getLineNumber(); 41 | 42 | callInfo = className + "." + methodName + ":" + lineNumber+ " - "; 43 | return callInfo; 44 | } 45 | 46 | public static void trace(Object message) { 47 | getCurrentLog().trace(message); 48 | } 49 | 50 | public static void trace(Object message, Throwable t) { 51 | getCurrentLog().trace(message, t); 52 | } 53 | 54 | public static void debug(Object message) { 55 | 56 | getCurrentLog().debug(getCallInfo() + message); 57 | } 58 | 59 | public static void debug(Object message, Throwable t) { 60 | getCurrentLog().debug(getCallInfo() + message, t); 61 | } 62 | 63 | public static void error(Object message) { 64 | 65 | getCurrentLog().error(getCallInfo() + message); 66 | } 67 | 68 | public static void error(Object message, Throwable t) { 69 | getCurrentLog().error(getCallInfo() + message, t); 70 | } 71 | 72 | public static void fatal(Object message) { 73 | getCurrentLog().fatal(getCallInfo() + message); 74 | } 75 | 76 | public static void fatal(Object message, Throwable t) { 77 | getCurrentLog().fatal(getCallInfo() + message, t); 78 | } 79 | 80 | public static void info(Object message) { 81 | 82 | getCurrentLog().info(getCallInfo() + message); 83 | } 84 | 85 | public static void info(Object message, Throwable t) { 86 | getCurrentLog().info(getCallInfo() + message, t); 87 | } 88 | 89 | public static void warn(Object message) { 90 | getCurrentLog().warn(getCallInfo() + message); 91 | } 92 | 93 | public static void warn(Object message, Throwable t) { 94 | getCurrentLog().warn(getCallInfo() + message, t); 95 | } 96 | } -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/ExcelUtility.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileOutputStream; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import org.apache.poi.xssf.usermodel.XSSFCell; 9 | import org.apache.poi.xssf.usermodel.XSSFRow; 10 | import org.apache.poi.xssf.usermodel.XSSFSheet; 11 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 12 | 13 | public class ExcelUtility { 14 | private XSSFSheet excelSheet; 15 | private XSSFWorkbook excelWorkbook; 16 | private XSSFCell cell; 17 | private XSSFRow row; 18 | 19 | public void setExcelFile(String sheetPath,String sheetName) throws Exception { 20 | try{ 21 | //Log.info("Getting sheets from the workbook."); 22 | FileInputStream excelFile = new FileInputStream(sheetPath); 23 | excelWorkbook = new XSSFWorkbook(excelFile); 24 | excelSheet = excelWorkbook.getSheet(sheetName); 25 | } catch(Exception exp){ 26 | Log.error("Exception occured in setExcelFile: "+exp.getMessage()); 27 | throw(exp); 28 | } 29 | } 30 | 31 | private int getTestCaseRow(String testCaseName, int testCaseColumn) throws Exception{ 32 | int row; 33 | try{ 34 | int rowCount = excelSheet.getLastRowNum(); 35 | for(row=0; row< rowCount; row++){ 36 | if(getCellData(row, testCaseColumn).equalsIgnoreCase(testCaseName)){ 37 | break; 38 | } 39 | } 40 | } 41 | catch(Exception exp){ 42 | Log.error("Exception occured in getTestCaseRow: "+exp.getMessage()); 43 | throw(exp); 44 | } 45 | 46 | return row; 47 | } 48 | 49 | public String getCellData(int rowNumb, int colNumb) throws Exception{ 50 | try{ 51 | cell = excelSheet.getRow(rowNumb).getCell(colNumb); 52 | //Log.info("Getting cell data."); 53 | if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { 54 | cell.setCellType(XSSFCell.CELL_TYPE_STRING); 55 | } 56 | String cellData = cell.getStringCellValue(); 57 | return cellData; 58 | } 59 | catch(Exception exp){ 60 | return ""; 61 | } 62 | } 63 | 64 | public void setCellData(String result, int rowNumb, int colNumb, String excelFilePath) throws Exception{ 65 | try{ 66 | row = excelSheet.getRow(rowNumb); 67 | cell = row.getCell(colNumb); 68 | Log.info("Setting results into the excel sheet."); 69 | if(cell==null){ 70 | cell = row.createCell(colNumb); 71 | cell.setCellValue(result); 72 | } 73 | else{ 74 | cell.setCellValue(result); 75 | } 76 | 77 | Log.info("Creating file output stream."); 78 | FileOutputStream fileOut = new FileOutputStream(excelFilePath); 79 | excelWorkbook.write(fileOut); 80 | fileOut.flush(); 81 | fileOut.close(); 82 | 83 | }catch(Exception exp){ 84 | Log.error("Exception occured in setCellData: "+exp.getMessage()); 85 | throw (exp); 86 | } 87 | } 88 | 89 | public Map getData(String testCaseName, String sheetPath,String sheetName) { 90 | Map dataMap = new HashMap(); 91 | try { 92 | setExcelFile(sheetPath, sheetName); 93 | int dataRow = getTestCaseRow(testCaseName.trim(), 0); 94 | int columnCount = excelSheet.getRow(dataRow).getLastCellNum(); 95 | for(int i=0;i")+2)); 29 | } 30 | 31 | @Override 32 | public void afterClickOn(WebElement element, WebDriver driver) { 33 | 34 | } 35 | 36 | @Override 37 | public void afterFindBy(By by, WebElement element, WebDriver driver) { 38 | 39 | } 40 | 41 | @Override 42 | public void afterGetScreenshotAs(OutputType target, X screenshot) { 43 | Log.info("Screen shot was taken successfully."); 44 | } 45 | 46 | @Override 47 | public void afterGetText(WebElement element, WebDriver driver, String text) { 48 | new ElementOperations(driver).highlightElement(element); 49 | Log.info("Captured Text message: "+text); 50 | } 51 | 52 | @Override 53 | public void afterNavigateBack(WebDriver driver) { 54 | Log.info("Navigated back to previous page "+driver.getCurrentUrl()); 55 | } 56 | 57 | @Override 58 | public void afterNavigateForward(WebDriver driver) { 59 | Log.info("Navigated back to forward "+driver.getCurrentUrl()); 60 | } 61 | 62 | @Override 63 | public void afterNavigateRefresh(WebDriver driver) { 64 | Log.info("Refreshed the current page"); 65 | } 66 | 67 | @Override 68 | public void afterNavigateTo(String url, WebDriver driver) { 69 | System.out.println("Navigated to: "+url); 70 | } 71 | 72 | @Override 73 | public void afterScript(String text, WebDriver driver) { 74 | 75 | } 76 | 77 | @Override 78 | public void afterSwitchToWindow(String windowName, WebDriver driver) { 79 | Log.info("Switched to new Window: "+windowName); 80 | } 81 | 82 | @Override 83 | public void beforeAlertAccept(WebDriver driver) { 84 | 85 | } 86 | 87 | @Override 88 | public void beforeAlertDismiss(WebDriver driver) { 89 | 90 | } 91 | 92 | @Override 93 | public void beforeChangeValueOf(WebElement element, WebDriver driver, CharSequence[] keysToSend) { 94 | 95 | } 96 | 97 | @Override 98 | public void beforeClickOn(WebElement element, WebDriver driver) { 99 | 100 | } 101 | 102 | @Override 103 | public void beforeFindBy(By by, WebElement element, WebDriver driver) { 104 | Log.info("The searching for webelement using "+ by.toString() + " has started."); 105 | } 106 | 107 | @Override 108 | public void beforeGetScreenshotAs(OutputType target) { 109 | 110 | } 111 | 112 | @Override 113 | public void beforeGetText(WebElement element, WebDriver driver) { 114 | 115 | } 116 | 117 | @Override 118 | public void beforeNavigateBack(WebDriver driver) { 119 | 120 | } 121 | 122 | @Override 123 | public void beforeNavigateForward(WebDriver driver) { 124 | 125 | } 126 | 127 | @Override 128 | public void beforeNavigateRefresh(WebDriver driver) { 129 | 130 | } 131 | 132 | @Override 133 | public void beforeNavigateTo(String url, WebDriver driver) { 134 | 135 | } 136 | 137 | @Override 138 | public void beforeScript(String text, WebDriver driver) { 139 | 140 | } 141 | 142 | @Override 143 | public void beforeSwitchToWindow(String windowName, WebDriver driver) { 144 | Log.info("Current Window: "+windowName); 145 | } 146 | 147 | @Override 148 | public void onException(Throwable throwable, WebDriver driver) { 149 | Log.error("Exception occured: ",throwable); 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /src/test/java/com/automationpractice/runner/TestBase.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.runner; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | import java.nio.file.Files; 6 | import java.nio.file.Paths; 7 | import java.util.concurrent.TimeUnit; 8 | 9 | import org.openqa.selenium.OutputType; 10 | import org.openqa.selenium.TakesScreenshot; 11 | import org.openqa.selenium.WebDriver; 12 | import org.openqa.selenium.chrome.ChromeDriver; 13 | import org.openqa.selenium.chrome.ChromeOptions; 14 | import org.openqa.selenium.support.events.EventFiringWebDriver; 15 | import org.testng.ITestResult; 16 | import org.testng.annotations.AfterMethod; 17 | import org.testng.annotations.BeforeMethod; 18 | import org.testng.annotations.BeforeSuite; 19 | 20 | import com.automationpractice.listener.WebDriverListener; 21 | import com.automationpractice.utility.AllureConfigurator; 22 | import com.automationpractice.utility.ConfigReader; 23 | import com.automationpractice.utility.DriverManager; 24 | import com.automationpractice.utility.Log; 25 | import com.automationpractice.utility.ReportManager; 26 | import com.automationpractice.utility.ScreenshotUtility; 27 | import com.aventstack.extentreports.MediaEntityBuilder; 28 | 29 | import io.github.bonigarcia.wdm.WebDriverManager; 30 | import io.qameta.allure.Attachment; 31 | 32 | public class TestBase { 33 | 34 | @BeforeSuite 35 | public void configuringLog4j() throws IOException { 36 | AllureConfigurator.configure(); 37 | } 38 | 39 | @BeforeMethod 40 | public void browserSetup() { 41 | launchBrowser(ConfigReader.getProperty("appUrl")); 42 | } 43 | 44 | @AfterMethod (alwaysRun = true) 45 | public void browserTeardown(ITestResult result) { 46 | WebDriver driver = DriverManager.getInstance().getDriver(); 47 | String testCaseName = result.getMethod().getConstructorOrMethod().getName(); 48 | if(result.getStatus() == ITestResult.FAILURE) { 49 | try { 50 | saveTextLog(testCaseName+" Failed, Please find the attached screenshot"); 51 | saveScreenshot(driver); 52 | String imageFilePath = ScreenshotUtility.takeFullScreenShot(driver, testCaseName+"_Failed"); 53 | ReportManager.getTest().error("Screenshot", MediaEntityBuilder.createScreenCaptureFromPath(imageFilePath).build()); 54 | } catch (IOException e) { 55 | e.printStackTrace(); 56 | Log.error("Error occured while attaching screenshot: "+e.getMessage()); 57 | } 58 | } 59 | DriverManager.getInstance().getEventFiringWebDriver().unregister(DriverManager.getInstance().getWebDriverListener()); 60 | closeBrowser(driver); 61 | } 62 | 63 | public WebDriver launchBrowser(String url){ 64 | System.out.println("Launching Browser."); 65 | WebDriverManager.chromedriver().arch32().setup(); 66 | ChromeOptions option = new ChromeOptions(); 67 | option.addArguments("--disable-infobars"); 68 | option.addArguments("--incognito"); 69 | WebDriver driver = new ChromeDriver(option); 70 | EventFiringWebDriver eventHandler = new EventFiringWebDriver(driver); 71 | WebDriverListener listener = new WebDriverListener(); 72 | eventHandler.register(listener); 73 | driver = eventHandler; 74 | DriverManager.getInstance().setWebDriverListener(listener); 75 | DriverManager.getInstance().setEventFiringWebDriver(eventHandler); 76 | DriverManager.getInstance().setDriver(driver); 77 | driver.get(url); 78 | driver.manage().window().maximize(); 79 | driver.manage().timeouts().implicitlyWait(Long.parseLong(ConfigReader.getProperty("implicitlyWaitTime")),TimeUnit.SECONDS); 80 | return driver; 81 | } 82 | 83 | public void closeBrowser(WebDriver driver){ 84 | System.out.println("Closing Browser."); 85 | driver.quit(); 86 | } 87 | 88 | // Image attachments for Allure 89 | @Attachment(value = "Page screenshot", type = "image/png") 90 | public byte[] saveScreenshot(WebDriver driver) { 91 | return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES); 92 | } 93 | 94 | // Text attachments for Allure 95 | @Attachment(value = "{0}", type = "text/plain") 96 | public static String saveTextLog(String message) { 97 | return message; 98 | } 99 | 100 | // HTML attachments for Allure 101 | @Attachment(value = "{0}", type = "text/html") 102 | public static String attachHtml(String html) { 103 | return html; 104 | } 105 | 106 | // Video attachments for Allure 107 | @Attachment(value = "video",type="video/webm") 108 | public byte[] attachVideo(String path) throws Exception { 109 | return Files.readAllBytes(Paths.get(new File(path).getAbsolutePath())); 110 | } 111 | 112 | } 113 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | com.automationpractice 6 | DataDrivenFramework-sample 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | DataDrivenFramework-sample 11 | http://maven.apache.org 12 | 13 | 14 | UTF-8 15 | 1.8.10 16 | ${basedir}/testng.xml 17 | 2 18 | false 19 | surefire.testng.verbose 20 | 10 21 | 22 | 23 | 24 | 25 | org.apache.maven.plugins 26 | maven-compiler-plugin 27 | 3.6.0 28 | 29 | 1.8 30 | 1.8 31 | 32 | 33 | 34 | org.apache.maven.plugins 35 | maven-surefire-plugin 36 | 3.0.0-M3 37 | true 38 | 39 | 40 | test 41 | 42 | test 43 | 44 | 45 | 46 | 47 | 48 | ${suiteXmlFile} 49 | 50 | ${skipTests} 51 | true 52 | 53 | -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar" 54 | 55 | methods 56 | ${parallel.thread} 57 | 58 | 59 | 60 | org.aspectj 61 | aspectjweaver 62 | ${aspectj.version} 63 | 64 | 65 | 66 | 67 | org.apache.maven.plugins 68 | maven-plugin-plugin 69 | 3.6.0 70 | 71 | plugin 72 | target/dir 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | org.testng 82 | testng 83 | 7.7.0 84 | 85 | 86 | 87 | org.seleniumhq.selenium 88 | selenium-java 89 | 3.141.59 90 | 91 | 92 | 93 | org.apache.poi 94 | poi 95 | 4.1.1 96 | 97 | 98 | 99 | org.apache.poi 100 | poi-ooxml 101 | 3.17 102 | 103 | 104 | 105 | org.apache.logging.log4j 106 | log4j-core 107 | 2.17.1 108 | 109 | 110 | 111 | commons-io 112 | commons-io 113 | 2.14.0 114 | 115 | 116 | 117 | com.aventstack 118 | extentreports 119 | 3.1.5 120 | 121 | 122 | 123 | ru.yandex.qatools.ashot 124 | ashot 125 | 1.5.4 126 | 127 | 128 | 129 | org.apache.httpcomponents 130 | httpmime 131 | 4.5.8 132 | 133 | 134 | io.qameta.allure 135 | allure-testng 136 | 2.13.0 137 | 138 | 139 | 140 | io.github.bonigarcia 141 | webdrivermanager 142 | 4.2.2 143 | 144 | 145 | 146 | com.automation-remarks 147 | video-recorder-testng 148 | 2.0 149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /src/main/java/com/automationpractice/utility/ElementOperations.java: -------------------------------------------------------------------------------- 1 | package com.automationpractice.utility; 2 | 3 | import java.util.LinkedList; 4 | import java.util.List; 5 | import java.util.Set; 6 | 7 | import org.openqa.selenium.Alert; 8 | import org.openqa.selenium.By; 9 | import org.openqa.selenium.JavascriptExecutor; 10 | import org.openqa.selenium.NoAlertPresentException; 11 | import org.openqa.selenium.NoSuchElementException; 12 | import org.openqa.selenium.WebDriver; 13 | import org.openqa.selenium.WebElement; 14 | import org.openqa.selenium.interactions.Actions; 15 | import org.openqa.selenium.support.ui.ExpectedConditions; 16 | import org.openqa.selenium.support.ui.Select; 17 | import org.openqa.selenium.support.ui.WebDriverWait; 18 | 19 | public class ElementOperations { 20 | private Long waitTime = Long.parseLong(ConfigReader.getProperty("webDriverWaitTime")); 21 | private WebDriver driver = null; 22 | 23 | public ElementOperations(WebDriver driver) { 24 | this.driver = driver; 25 | } 26 | 27 | public void highlightElement(WebElement element) { 28 | JavascriptExecutor js = (JavascriptExecutor) driver; 29 | js.executeScript("arguments[0].style.border='4px solid yellow'", element); 30 | pause(1); 31 | js.executeScript("arguments[0].style.border=''", element); 32 | } 33 | 34 | public void clickOnWebElement(WebElement element){ 35 | ((JavascriptExecutor)driver).executeScript("arguments[0].click();",element); 36 | } 37 | 38 | public void selectByVisibleText(WebElement element, String visibleText){ 39 | Select select = new Select(element); 40 | select.selectByVisibleText(visibleText); 41 | } 42 | 43 | public void selectByIndex(WebElement element, int index){ 44 | Select select = new Select(element); 45 | select.selectByIndex(index); 46 | } 47 | 48 | public String getSelectedValue(WebElement element) { 49 | String value = new Select(element).getFirstSelectedOption().getText(); 50 | Log.info("Selected Value : "+ value); 51 | return value; 52 | } 53 | 54 | public List getAllSelectedValues(WebElement locator) { 55 | Select select = new Select(locator); 56 | List elementList = select.getAllSelectedOptions(); 57 | return getListValue(elementList); 58 | } 59 | 60 | public List getAllDropDownValues(WebElement locator) { 61 | Select select = new Select(locator); 62 | List elementList = select.getOptions(); 63 | return getListValue(elementList); 64 | } 65 | 66 | private List getListValue(List elementList) { 67 | List valueList = new LinkedList(); 68 | 69 | for (WebElement element : elementList) { 70 | Log.info(element.getText()); 71 | valueList.add(element.getText()); 72 | } 73 | return valueList; 74 | } 75 | 76 | public void waitForvisibilityOfElement(WebElement element){ 77 | WebDriverWait wait = new WebDriverWait(driver, waitTime); 78 | wait.until(ExpectedConditions.visibilityOf(element)); 79 | } 80 | 81 | public void waitForElementToBeClickable(WebElement element){ 82 | WebDriverWait wait = new WebDriverWait(driver, waitTime); 83 | wait.until(ExpectedConditions.elementToBeClickable(element)); 84 | } 85 | 86 | public void waitForWindowsToOpen(int numberOfWindow){ 87 | WebDriverWait wait = new WebDriverWait(driver, waitTime); 88 | wait.until(ExpectedConditions.numberOfWindowsToBe(numberOfWindow)); 89 | } 90 | 91 | public boolean isElementPresent(By byElement) { 92 | try{ 93 | driver.findElement(byElement); 94 | Log.info("Element is present"); 95 | return true; 96 | }catch(Exception exp){ 97 | Log.info("Element is NOT present"); 98 | return false; 99 | } 100 | } 101 | 102 | public void switchToFrame(WebElement element) { 103 | driver.switchTo().frame(element); 104 | Log.info("Switched to new frame"); 105 | } 106 | 107 | public void switchToFrame(String nameOrId) { 108 | driver.switchTo().frame(nameOrId); 109 | Log.info("Switched to new frame"); 110 | } 111 | 112 | public void switchToParentFrame() { 113 | driver.switchTo().parentFrame(); 114 | Log.info("Switched to Parent Frame"); 115 | } 116 | 117 | public void switchToParentWindow() { 118 | driver.switchTo().defaultContent(); 119 | Log.info("Switched to Parent Window"); 120 | } 121 | 122 | public void switchToNewWindow() { 123 | String mainWindow = driver.getWindowHandle(); 124 | Set windowHandles = driver.getWindowHandles(); 125 | Log.info("Number of Windows: "+windowHandles.size()); 126 | for (String handle: windowHandles) { 127 | if (!mainWindow.equals(handle)) { 128 | driver.switchTo().window(handle); 129 | driver.manage().window().maximize(); 130 | Log.info("Switched to New Window with Title: "+driver.getTitle()); 131 | } 132 | } 133 | } 134 | 135 | public void switchToParentWithChildClose() { 136 | String mainWindow = driver.getWindowHandle(); 137 | Set windowHandles = driver.getWindowHandles(); 138 | Log.info("Number of Windows: "+windowHandles.size()); 139 | int i=1; 140 | for (String handle: windowHandles) { 141 | if (!mainWindow.equals(handle)) { 142 | driver.switchTo().window(handle); 143 | driver.close(); 144 | Log.info("Closed Child Window: "+i); 145 | i++; 146 | } 147 | } 148 | driver.switchTo().window(mainWindow); 149 | } 150 | 151 | public void pause(int seconds){ 152 | try { 153 | Thread.sleep(seconds*1000); 154 | } catch (InterruptedException e) { 155 | e.printStackTrace(); 156 | } 157 | } 158 | 159 | public void scrollToElement(WebElement element){ 160 | ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element); 161 | } 162 | 163 | public void scrollToBottom(){ 164 | ((JavascriptExecutor)driver).executeScript("window.scrollTo(0, document.body.scrollHeight)"); 165 | } 166 | 167 | public void scrollToTop(){ 168 | ((JavascriptExecutor)driver).executeScript("window.scrollTo(0, -document.body.scrollHeight)"); 169 | } 170 | 171 | public void zoomInByPercentage(String percentage){ 172 | ((JavascriptExecutor)driver).executeScript("document.body.style.zoom='"+percentage+"%'"); 173 | } 174 | 175 | public void waitForAlert(){ 176 | WebDriverWait wait = new WebDriverWait(driver, waitTime); 177 | wait.until(ExpectedConditions.alertIsPresent()); 178 | } 179 | 180 | public String getAlertMessageAndAccept(){ 181 | String message = null; 182 | try { 183 | waitForAlert(); 184 | Alert alert = driver.switchTo().alert(); 185 | message = alert.getText(); 186 | Log.info("Alert message: "+message); 187 | alert.accept(); 188 | }catch (Exception e) { 189 | Log.info("Alert was not present"); 190 | } 191 | return message; 192 | } 193 | 194 | public String getAlertMessageAndDismiss(){ 195 | String message = null; 196 | try { 197 | waitForAlert(); 198 | Alert alert = driver.switchTo().alert(); 199 | message = alert.getText(); 200 | Log.info("Alert message: "+message); 201 | alert.dismiss(); 202 | }catch (Exception e) { 203 | Log.info("Alert was not present"); 204 | } 205 | return message; 206 | } 207 | 208 | public boolean isAlertPresent() { 209 | try{ 210 | driver.switchTo().alert(); 211 | return true; 212 | }catch (NoAlertPresentException exp){ 213 | return false; 214 | } 215 | } 216 | 217 | public boolean isVisible(WebElement element) { 218 | try{ 219 | waitForvisibilityOfElement(element); 220 | return element.isDisplayed(); 221 | }catch (NoSuchElementException exp){ 222 | return false; 223 | } 224 | } 225 | 226 | public void selectCheckbox(boolean clickOnCheckbox, WebElement element) { 227 | if(clickOnCheckbox && !element.isSelected()) { 228 | element.click(); 229 | } 230 | else if(!clickOnCheckbox && element.isSelected()) { 231 | element.click(); 232 | } 233 | } 234 | 235 | public void doubleClick(WebElement element) { 236 | Actions action = new Actions(driver); 237 | action.moveToElement(element).doubleClick().build().perform(); 238 | } 239 | } 240 | --------------------------------------------------------------------------------