Package Layout
- src
- log4j2.xml - log4j2 Configuration
- pom.xml - Maven Configuration
- testng.xml - TestNG Configuration
- com.us.test.selenium
- Main
- com.us.test.selenium.pageactions
- Home_Actions
- com.us.test.selenium.pageobjects
- Home_Page
- PageBaseClass
- com.us.test.selenium.tests
- Login_Home
- com.us.test.selenium.tests.testdata
- TestData.xls
- com.us.test.selenium.util
- BrowserUtils
- Constant
- ElementUtils
- ExcelUtils
- LIstener
- Listeners
- TestLog
Classes
com.uc.test.selenium
Main
com.uc.test.selenium.pageobjects
PageBaseClass
package com.uc.test.selenium.pageobjects; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; public class PageBaseClass { public static WebDriver driver; public static boolean bResult; public PageBaseClass(WebDriver driver){ PageBaseClass.driver = driver; driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); PageBaseClass.bResult = true; } }
Home_Page
package com.uc.test.selenium.pageobjects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.WebDriverWait; import com.uc.test.selenium.util.BrowserUtils; //import utility.TestLog; public class Home_Page extends PageBaseClass { private static WebElement element = null; public Home_Page(WebDriver driver){ super(driver); } public static WebElement link_Error() throws Exception{ try{ element = driver.findElement(By.xpath ("//a[contains(.,'Error')]")); }catch (Exception e){ throw(e); } return element; } public static WebElement link_Home() throws Exception{ try{ element = driver.findElement(By.xpath("//a[contains(.,'Home')]")); }catch (Exception e){ throw(e); } return element; } public static WebElement link_Music() throws Exception{ try{ element = driver.findElement(By.xpath ("//a[contains(.,'Music')]")); }catch (Exception e){ throw(e); } return element; } public static WebElement txtbx_Search() throws Exception{ try{ element = driver.findElement(By.id("edit-keys")); }catch (Exception e){ throw(e); } return element; } public static WebElement btn_Search() throws Exception{ try{ element = driver.findElement(By.id("edit-submit")); }catch (Exception e){ throw(e); } return element; } public static WebElement link_CreateArtcle() throws Exception{ try { element = driver.findElement(By.xpath("//a[@href='/uc/node/add/article']")); } catch (Exception e) { e.printStackTrace(); } return element; } public static WebElement link_Computing() throws Exception{ try{ element = driver.findElement(By.xpath ("//a[@href='/uc/computing']")); }catch (Exception e){ throw(e); } return element; } public static WebElement link_Login() throws Exception{ int timeoutSec = 15; WebDriverWait wait = new WebDriverWait(driver, timeoutSec); //wait.until((driver) -> driver.findElements(By.xpath("//a[@href='/uc/user/login']")).size()>0); wait.until((driver) -> driver.findElement(By.xpath("//a[@href='/uc/user/login']")).isDisplayed()); //BrowserUtils.waitForElementToBeReady("xpath", "//a[@href='/uc/user/login']"); try { element = driver.findElement(By.xpath("//a[@href='/uc/user/login']")); } catch (Exception e) { e.printStackTrace(); } return element; } public static WebElement link_ShortcutsToggle() throws Exception{ try { if ( !driver.findElement(By.xpath("//a[@href='/uc/node/add/article']")).isDisplayed() ) { driver.findElement(By.id("toolbar-item-shortcuts")).click(); } } catch (Exception e) { e.printStackTrace(); } return element; } }
com.uc.test.selenium.pageactions
Home_Actions
package com.uc.test.selenium.pageactions; import com.uc.test.selenium.pageobjects.Home_Page; public class Home_Actions { public static void Execute(int iTestCaseRow) throws Exception{ // Here we are sending the UserName string to the UserName Textbox on the LogIN Page // This is call Page Object Model (POM) // For use of POM, please see http://www.toolsqa.com/page-object-model/ //Home_Page.txtbx_Username().sendKeys(sUserName); Home_Page.link_Home().click(); Home_Page.link_Music().click(); } }
com.uc.test.selenium.tests
Test_Login
package com.uc.test.selenium.tests; //import org.apache.log4j.xml.DOMConfigurator; //import org.apache.logging.log4j.core.config.xml.*; import org.openqa.selenium.WebDriver; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.asserts.*; //import org.apache.log4j.xml.DOMConfigurator; import com.uc.test.selenium.pageobjects.CreateArticle_Page; import com.uc.test.selenium.pageobjects.Home_Page; import com.uc.test.selenium.pageobjects.Login_Page; import com.uc.test.selenium.pageobjects.PageBaseClass; import com.uc.test.selenium.util.BrowserUtils; import com.uc.test.selenium.util.Constant; import com.uc.test.selenium.util.ExcelUtils; import com.uc.test.selenium.util.TestLog; //import com.uc.test.selenium.util.TestLog; public class Test_Login { public WebDriver driver; @BeforeMethod public void beforeMethod() throws Exception { driver = BrowserUtils.OpenBrowser(); new PageBaseClass(driver); } @AfterMethod public void afterMethod() throws Exception { driver.quit(); } @Test public void test_1() throws Exception { try { //Logger Actions //DOMConfigurator.configure("log4j2.xml"); // // Excel Actions ExcelUtils.setExcelFile("W:\\w\\svn\\java\\SeleniumFramework\\src\\com\\uc\\test\\selenium\\tests\\testdata\\TestData.xlsx", "Sheet1"); String sTestCaseName = "ECOIOT391"; int iTestCaseRow; iTestCaseRow = ExcelUtils.getRowContains(sTestCaseName,Constant.DataSheet.Col_TestCaseName.ordinal()); String sUserName = ExcelUtils.getCellData(iTestCaseRow, Constant.DataSheet.Col_UserName.ordinal()); TestLog.startTestCase(sTestCaseName); TestLog.info("TestCaseRow=" + String.valueOf(iTestCaseRow)); // WebDriver Actions BrowserUtils.BrowserGet(); Home_Page.txtbx_Search().sendKeys("1234"); Thread.sleep(100); Home_Page.btn_Search().click(); Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); throw(e); } } @Test public void test_2() throws Exception { try { BrowserUtils.BrowserGet(); Thread.sleep(3000); Home_Page.link_Computing().click(); Thread.sleep(3000); } catch (Exception e) { throw(e); } } @Test public void test_createArticle() throws Exception{ try { BrowserUtils.BrowserGet(); //Thread.sleep(2000); //BrowserUtils.waitForPageToBeReady(); Home_Page.link_Login().click(); Login_Page.txtbx_Username().sendKeys("UnityAdmin"); Login_Page.txtbx_Password().sendKeys("UnityAdmin@2017"); Login_Page.btn_Login().click(); Home_Page.link_ShortcutsToggle(); Home_Page.link_CreateArtcle().click(); CreateArticle_Page.txtbx_Title().sendKeys("ArticleTitle"); CreateArticle_Page.txtbx_Body().sendKeys("1234"); CreateArticle_Page.txtbx_Tags().sendKeys("_deleteme"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); Assert.assertEquals(false, true, "Test Failed"); } } @Test public void test_3() throws Exception { try { BrowserUtils.BrowserGet(); Thread.sleep(3000); Home_Page.link_Error().click(); Thread.sleep(3000); } catch (Exception e) { throw(e); } } }
com.uc.test.selenium.tests.testdata
TestData.xls
com.uc.test.selenium.util
- following code excerpts are commented in various places as they are under active development, namely the log4j wiring/config
BrowserUtils
package com.uc.test.selenium.util; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.firefox.internal.ProfilesIni; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; //import utility.TestLog; //import utility.Constant; //import utility.ExcelUtils; //import utility.TestLog; public class BrowserUtils { // this instance is for building up 'driver' with properties before passing to // PageBaseClass for use in tests public static WebDriver driver = null; private static WebElement element; /** * Returns a Webdriver object that has been pre-populated with applicable profile * This WebDriver is statically declared/called but returns a 'driver' object * that will be instantiated with new by the rest of the framework * <p> * The non-static PageBaseClass will accept this returned WebDriver object * and then create another 'driver' object that can use used by NON-STATIC * methods * * @return WebDriver Object, ready for Firefox * @throws Exception if WebDriver can't be instantiated * @see WebDriver * */ // public static WebDriver OpenBrowser(int iTestCaseRow) throws Exception{ public static WebDriver OpenBrowser() throws Exception{ String sBrowserName, sPlatform; try{ sBrowserName = "Mozilla"; sPlatform = "WINDOWS"; if(sBrowserName.equalsIgnoreCase("Mozilla")){ driver = CreateDriverFireFox(sPlatform); } else if(sBrowserName.equalsIgnoreCase("Chrome")){ driver = CreateDriverFireFox(sPlatform); } } catch (Exception e) { throw(e); } return driver; } //end method private static WebDriver CreateDriverFireFox(String sPlatform) { // Configure Firefox for cookies acceptance FirefoxProfile profile = new ProfilesIni().getProfile("default"); profile.setPreference("network.cookie.cookieBehavior", 0); if (sPlatform.equals("WINDOWS")){ // Configure Firefox Gecko Driver // 0.20.0 //System.setProperty("webdriver.gecko.driver","W:\\w\\Java\\lib\\Selenium.3.11.0\\SeleniumWebDrivers\\geckodriver\\geckodriver-v0.20.1-win64\\geckodriver.exe"); // 0.19.1 //System.setProperty("webdriver.gecko.driver","W:\\w\\tools\\SeleniumWebDrivers\\geckodriver\\geckodriver-v0.19.1-win64\\geckodriver.exe"); System.setProperty("webdriver.gecko.driver","res\\geckodriver\\geckodriver-v0.19.1-win64\\geckodriver.exe"); } if (sPlatform.equalsIgnoreCase("LINUX")){ // Configure Firefox Gecko Driver System.setProperty("webdriver.gecko.driver","res/geckodriver/geckodriver-v0.19.1-linux64/geckodriver.exe"); } if (sPlatform.equalsIgnoreCase("MACOS")){ // Configure Firefox Gecko Driver System.setProperty("webdriver.gecko.bin","/Applications/Firefox.app/Contents/MacOS/firefox-bin"); System.setProperty("webdriver.gecko.driver","geckodriver"); } // Create web driver driver = new FirefoxDriver(); // driver = new FirefoxDriver(); // TestLog.info("New driver instantiated"); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS); return driver; } private static WebDriver CreateDriverChrome(String sPlatform) { //Configure Chrome for cookies acceptance //ChromeProfile profile = new ProfilesIni().getProfile("default"); //profile.setPreference("network.cookie.cookieBehavior", 0); if (sPlatform.equals("WINDOWS")){ System.setProperty("webdriver.chrome.driver","res\\chromedriver\\chromedriver-v2.40.0-win64\\chromedriver.exe"); } if (sPlatform.equalsIgnoreCase("LINUX")){ // Configure Chrome Driver System.setProperty("webdriver.chrome.driver","res/chromedriver/chromedriver-v2.40.0-linux64/chromedriver.exe"); } if (sPlatform.equalsIgnoreCase("MACOS")){ // Configure Chrome Driver //System.setProperty("webdriver.gecko.bin","/Applications/Firefox.app/Contents/MacOS/firefox-bin"); System.setProperty("webdriver.chrome.driver","chromedriver"); } // Create web driver driver = new ChromeDriver(); // TestLog.info("New driver instantiated"); driver.manage().deleteAllCookies(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS); return driver; } public static void BrowserClose() { driver.close(); driver.quit(); } public static void BrowserGet() { driver.get("http://www.unityconstruct.org"); } public static void waitForElementToBeReady(String elType, String elTypeIdentifier) { WebDriverWait wait = new WebDriverWait(driver, 10); switch (elType) { case "xpath": element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(elTypeIdentifier))); break; case "id": element = wait.until(ExpectedConditions.elementToBeClickable(By.id(elTypeIdentifier))); break; default: break; } } public static void waitForPageToBeReady() { JavascriptExecutor js = (JavascriptExecutor)driver; //This loop will rotate for 100 times to check If page Is ready after every 1 second. //You can replace your if you wants to Increase or decrease wait time. for (int i=0; i<30; i++) { if (js.executeScript("return document.readyState").toString().equals("complete") || js.executeScript("return document.readyState").toString().equals("complete")) { // TestLog.info("waitForPageToBeReady - executeScript complete [or loaded]"); break; } try { // TestLog.info("waitForPageToBeReady: Add Sleep time 1000 ms"); Thread.sleep(1000); }catch (InterruptedException e) {} //To check page ready state. } } }
Constant
package com.uc.test.selenium.util; public class Constant { public static final String URL = "https://www.unityconstruct.org"; public static final String Username = "super"; public static final String Password ="2wire"; //public static final String Path_TestData = ".//src//TestData/"; public static final String Path_TestData = ".//src//com//uc//test//selenium//tests//testdata//TestData.xlsx"; public static final String File_TestData = "TestData.xlsx"; public static final String Path_TestData2 = "W:\\w\\svn\\SeleniumFramework\\src\\com\\uc\\test\\selenium\\tests\\testdata\\TestData.xlsx"; //public static final String Path_log4j = ".//src//com//uc//test//selenium//tests//testdata//log4j2b.xml"; public static final String Path_log4j = ".//src//log4j2.xml"; // XPATH Library public enum LoginPageElements { LOGIN_TXT_USERNAME ("//id="), LOGIN_TXT_PASSWORD ("//id="), LOGIN_BTN_SUBMIT ("//id="); private String value; LoginPageElements(String value){ this.value = value; } public String getValue() { return value; } } public enum Wtf { one("a"), two("b"), three("c"); private final String letter; Wtf(String letter){ this.letter = letter; } private String letter() {return letter; } public String getLetter() { return letter(); } } //Test Data Sheet Columns // use .ordinal() to get its index for use as Col# public enum DataSheet { Col_TestCaseName, Col_URL, Col_UserName, Col_Password, Col_Browser, Col_Platform, Col_DUTSN, Col_TopMenu, Col_SubMenu, Col_Selection1, Col_Selection2, Col_Selection3, Col_Selection4, Col_DeviceSearch1, Col_DeviceSearch2, Col_DeviceSearch3, Col_DeviceSearch4, Col_DeviceSearch5, Col_DeviceView1, Col_DeviceView2, Col_DeviceView3, Col_DeviceView4, Col_DataSet1 , Col_DataSet2, Col_DataSet3, Col_TopMenuVerify, Col_SubMenuVerify, Col_SectionNameVerify, Col_TopMenuPrep, Col_SubMenuPrep, Col_Selectionprep1, Col_Selectionprep2, Col_Selectionprep3, Col_APIPrep1, Col_APIPrep2, Col_APIPrep3, Col_Result; private int value; public int getValue() { return value; } } public enum DBDataSheet { Col_TestCaseName, Col_DUTSN, Col_OUI, Col_DBHostURL, Col_DBUserName, Col_DBPassword, Col_DBService; private int value; public int getValue() { return value; } } public static final String Path_ScreenShot = "./src/Screenshots/"; }
ElementUtils
package com.uc.test.selenium.util; public class ElementUtils { }
ExcelUtils
package com.uc.test.selenium.util; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtils { private static XSSFSheet ExcelWSheet; private static XSSFWorkbook ExcelWBook; private static XSSFCell Excelcell; private static XSSFRow Excelrow; // This method is to set the File path and to open the Excel file, Pass Excel // Path and Sheetname as Arguments to this method public static void setExcelFile(String Path, String SheetName) throws Exception { try { // Open the Excel file FileInputStream ExcelFile = new FileInputStream(Path); // Access the required test data sheet ExcelWBook = new XSSFWorkbook(ExcelFile); ExcelWSheet = ExcelWBook.getSheet(SheetName); // TestLog.info("Excel sheet opened"); } catch (Exception e) { throw (e); } } // This method is to read the test data from the Excel cell, in this we are // passing parameters as Row num and Col num public static String getCellData(int RowNum, int ColNum) throws Exception { try { Excelcell = ExcelWSheet.getRow(RowNum).getCell(ColNum); String CellData = Excelcell.getStringCellValue(); return CellData; } catch (Exception e) { return ""; } } // This method is to write in the Excel cell, Row num and Col num are the // parameters @SuppressWarnings("static-access") public static void setCellData(String Result, int RowNum, int ColNum) throws Exception { try { Excelrow = ExcelWSheet.getRow(RowNum); Excelcell = Excelrow.getCell(ColNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); if (Excelcell == null) { Excelcell = Excelrow.createCell(ColNum); Excelcell.setCellValue(Result); } else { Excelcell.setCellValue(Result); } // Constant variables Test Data path and Test Data file name FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData + Constant.File_TestData); ExcelWBook.write(fileOut); fileOut.flush(); fileOut.close(); } catch (Exception e) { throw (e); } } public static int getRowContains(String sTestCaseName, int colNum) throws Exception { int i; try { int rowCount = ExcelUtils.getRowUsed(); for (i = 0; i < rowCount; i++) { if (ExcelUtils.getCellData(i, colNum).equalsIgnoreCase(sTestCaseName)) { break; } } return i; } catch (Exception e) { // TestLog.error("Class ExcelUtil | Method getRowContains | Exception desc : " + // e.getMessage()); throw (e); } } public static int getRowUsed() throws Exception { try { int RowCount = ExcelWSheet.getLastRowNum(); // TestLog.info("Total number of Row used return as < " + RowCount + " >."); return RowCount; } catch (Exception e) { // TestLog.error("Class ExcelUtil | Method getRowUsed | Exception desc : " + e.getMessage()); // System.out.println(e.getMessage()); throw (e); } } }
Listener
package com.uc.test.selenium.util; import org.testng.IInvokedMethod; import org.testng.IInvokedMethodListener; import org.testng.ITestContext; import org.testng.ITestListener; import org.testng.ITestNGMethod; import org.testng.ITestResult; import org.testng.Reporter; public class Listener implements ITestListener, IInvokedMethodListener { public void onFinish(ITestContext arg0) { Reporter.log("Completed executing test " + arg0.getName(), true); } public void onStart(ITestContext arg0) { Reporter.log("About to begin executing test " + arg0.getName(), true); } public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) { } public void onTestFailure(ITestResult arg0) { printTestResults(arg0); } private void printTestResults(ITestResult result) { Reporter.log("TestName = " + result.getTestName(), true); Reporter.log("Test Method resides in " + result.getTestClass().getName(), true); if (result.getParameters().length != 0) { String params = null; for (Object parameter : result.getParameters()) { params += parameter.toString() + ","; } Reporter.log("Test Method had the following parameters : " + params, true); } String status = null; switch (result.getStatus()) { case ITestResult.SUCCESS: status = "Pass"; break; case ITestResult.FAILURE: status = "Failed"; break; case ITestResult.SKIP: status = "Skipped"; } Reporter.log("Test Status: " + status, true); } public void onTestSkipped(ITestResult arg0) { printTestResults(arg0); } public void onTestStart(ITestResult arg0) { } public void onTestSuccess(ITestResult arg0) { printTestResults(arg0); } public void afterInvocation(IInvokedMethod arg0, ITestResult arg1) { String textMsg = "Completed executing " + returnMethodName(arg0.getTestMethod()); Reporter.log(textMsg, true); } public void beforeInvocation(IInvokedMethod arg0, ITestResult arg1) { String textMsg = "About to begin executing " + returnMethodName(arg0.getTestMethod()); Reporter.log(textMsg, true); } private String returnMethodName(ITestNGMethod method) { return method.getRealClass().getSimpleName() + "." + method.getMethodName(); } }
Listeners
package com.uc.test.selenium.util; import org.testng.ITestResult; import org.testng.Reporter; import org.testng.TestListenerAdapter; public class Listeners extends TestListenerAdapter { public void onTestFailure(ITestResult result) { String rs = getMethodContext(result); System.err.println(rs + " | FAILED"); Reporter.log(rs + " | FAILED"); } @Override public void onTestSkipped(ITestResult result) { String rs = getMethodContext(result); System.out.println(rs + " | SKIPPED"); Reporter.log(rs + " | SKIPPED"); } @Override public void onTestSuccess(ITestResult result) { String rs = getMethodContext(result); System.out.println(rs + " | PASSED"); Reporter.log(rs + " | PASSED"); } private String getMethodContext(ITestResult result) { // String browser = result.getTestContext().getCurrentXmlTest() // .getParameter("browser"); String testClasss = result.getTestClass().getName(); String name = result.getName(); String rs = testClasss + " | " + name; return rs; } }
TestLog
package com.uc.test.selenium.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class TestLog { private static final Logger logCommon = LogManager.getLogger("commons-log"); private static final Logger logAnalytics = LogManager.getLogger("analytics-log"); static final Logger Log = LogManager.getLogger(TestLog.class.getName()); // Initialize Log4j logs // private static Logger Log = Logger.getLogger(TestLog.class.getName()); // This is to print log for the beginning of the test case, as we usually run so many test cases as a test suite public static void startTestCase(String sTestCaseName){ Log.info("****************************************************************************************"); Log.info("****************************************************************************************"); Log.info("$$$$$$$$$$$$$$$$$$$$$ "+sTestCaseName+ " $$$$$$$$$$$$$$$$$$$$$$$$$"); Log.info("****************************************************************************************"); Log.info("****************************************************************************************"); } //This is to print log for the ending of the test case public static void endTestCase(String sTestCaseName){ Log.info("XXXXXXXXXXXXXXXXXXXXXXX "+"-E---N---D-"+" XXXXXXXXXXXXXXXXXXXXXX"); Log.info("X"); Log.info("X"); Log.info("X"); Log.info("X"); } // Need to create these methods, so that they can be called public static void info(String message) { Log.info(message); } public static void warn(String message) { Log.warn(message); } public static void error(String message) { Log.error(message); } public static void fatal(String message) { Log.fatal(message); } public static void debug(String message) { Log.debug(message); } }
- Log in to post comments