Selenium JAVA


For other tools and frameworks I used, please Visit my public Google Drive, and my GitHub

Steps

BrowserStep
package Steps;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Wait;

import java.util.HashMap;
import java.util.Map;

import static Helpers.Browser_Helper.getDriver;

public class BrowserStep {

private static WebDriver driver = getDriver();
static Wait<WebDriver> wait;

// // Invoke Browser
// // Go to URL
@When("^Go to URL - (.*)$")
public static void goToURL(String url){
driver.get(url);
System.out.println("\n Invoked URL = " + url);
}

    @Then("^Verify page title \"([^\"]*)\"$")
    public static void verifyTitle (String title) throws Exception {
    assert(driver.getTitle().contains(title));
    }

// // // Close Tab
@When("^Close Tab$")
public static void closeTab(){
driver.close();
}

// // // Kill Browser process
@When("^Kill the browser process$")
public static void quitBrowser(){
driver.quit();
}

// // Cookies and Cache
@When("^Delete All Cookies$")
public static void delAllCookies(){
driver.manage().deleteAllCookies();
System.out.println("\n Deleted All Cookies");
}

@When("^Delete one Cookie - (.*)$")
public static void delCookie(Cookie cookie){
driver.manage().deleteCookie(cookie);
System.out.println("\n Deleted Cookie = " + cookie);
}

@When("^Add one Cookie - (.*)$")
public static void addCookie(Cookie cookie){
driver.manage().addCookie(cookie);
System.out.println("\n Added one Cookie = " + cookie);
}


// // // Hover
@When("^Hover over element - (.*)$")
public static void HoverOver(WebElement element){
Actions hover = new Actions(driver);
hover.moveToElement(element).build().perform();
System.out.println("\n Hovering over element = " + element);
}

// // Scroll To
@When("^Scroll to element - (.*)$")
public static void scrollTo(WebElement element) throws InterruptedException{
Actions scroll = new Actions(driver);
scroll.moveToElement(element);
scroll.perform();
System.out.println("\n Scroll to element = " + element);
}

public static void justScroll() throws InterruptedException {
Actions scroll = new Actions(driver);
scroll.keyDown(Keys.ARROW_DOWN).perform();
scroll.keyDown(Keys.ARROW_DOWN).perform();
scroll.keyDown(Keys.ARROW_DOWN).perform();
scroll.keyDown(Keys.ARROW_DOWN).perform();
scroll.keyDown(Keys.ARROW_DOWN).perform();
Thread.sleep(1000);
}


@When("^Scroll into View of element - (.*)$")
public static void scrollToView(WebElement element) throws InterruptedException{
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
System.out.println("\n Scroll to element = " + element);
}

// // // Select between tabs
// For the main Tab
@When("^Focus on Main Window$")
public static void focusMain(){
for(String Main : driver.getWindowHandles()){
driver.switchTo().window(Main);
}
}

// For the New Tab
@When("^Shift Focus on New Tab$")
public static void focusNewTab(){
for(String newTab : driver.getWindowHandles()){
driver.switchTo().window(newTab);
}
}

// // // Upload File
@When("^Upload file - (.*)$")
public static void uploadFile(WebElement element, String filePath) {
element.sendKeys(filePath);
System.out.println("\n Uploaded File = " + filePath);
}

// // // Maximize Window
@When("^Maximize window$")
public static void full(){
driver.manage().window().maximize();
System.out.println("\n Window Maximied Fully");
}

// // // Minimize / Maximize to Window
@When("^Size browser to (\\d+) and (\\d+)$")
public static void minim(int h, int w){
Dimension s = new Dimension(h, w);
driver.manage().window().setSize(s);
System.out.println("\n Browser sized to = " + w + "x" + h);
}

@When("^Size Browser to half$")
public static void half(){
minim(1250, 1100);
System.out.println("\n Browser sized to half");
}

@When("^Size Browser to Tablet$")
public static void tablet(){
minim(800, 1000);
System.out.println("\n Browser sized to Tablet");
}

@When("^Size Browser to phone$")
public static void phone(){
minim(400, 700);
System.out.println("\n Browser sized to Phone");
}

// // //Get Current URL
@When("^Get Current URL")
public static void getURL(){
String currURL = driver.getCurrentUrl();
}

// // // Go back one page
@When("^Go back one page$")
public static void oneBack(){
driver.navigate().back();
}

// // // Go forward one page
@When("^Go forward one page$")
public static void oneForward(){
driver.navigate().forward();
}

// // // Refresh current page
@When("^Refresh page$")
public static void refresh(){
driver.navigate().refresh();
}

// Emulate Chrome to immitate mobile browser
@When("^Emulate Browser to Mobile Phone - (.*)$")
public static void emulateChrome(String phoneType){
Map<String, String> mobileEmulation = new HashMap<String, String>();
mobileEmulation.put("deviceName", phoneType);

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
driver = new ChromeDriver(chromeOptions);
}

    public static void err404(WebDriver driver) {
    if (driver.getCurrentUrl().contains("404 Page Not Found")){
    System.err.println("Invalid URL - Page Title = " + driver.getTitle());
}
}

}

DirectoryStep

package Steps;

import io.cucumber.java.en.And;
import io.cucumber.java.en.Then;

import java.io.File;

public class DirectoryStep {

@Then("^Get Latest File$")
public static File verify_latestFile(String path){
File dir = new File(path);
File[] files = dir.listFiles();
if (files == null || files.length == 0){
return dir;
}

File lastDownloadFile = files[0];
for (int i = 1; i < files.length; i++){
if (lastDownloadFile.lastModified() <files[i].lastModified()){
lastDownloadFile = files [i];
}
}
return lastDownloadFile;
}

@And("^Delete file$")
public static void delete_file(String file){
File delFile = new File(file);
if(delFile.exists()){
delFile.delete();
}
}
}




Data

DBQueries

package Data;

public class DBQueries {

public static String query;

public static String selLogin(String id){
query = "SELECT * FROM table WHERE id = " + id + "';";
return query;
}

public static String del_Login(String id){
query = "DELETE FROM table WHERE id = " + id + "';";
return query;
}

public static String count_Login(String id){
query = "SELECT DISTINCT COUNT (col_name) FROM table WHERE id = " + id + "';";
return query;
}

}


Helpers

Browser_Helper

package Helpers;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

public class Browser_Helper {

private static WebDriver driver;

public static WebDriver getDriver(){
if(driver == null){
driver = chooseDriver();
}
return driver;
}

public static WebDriver chooseDriver(){

String browser = System.getProperty("BROWSER");

if(browser == null) {
browser = System.getenv("BROWSER");

if (browser == null){
browser = "chrome";
}
}
String drPath = "C:\\Users\\Srilu Balla\\Documents\\IntelliJ_Workspace\\_CukeDrivers";
switch (browser){
case "chrome":
System.setProperty("webdriver.chrome.driver", drPath + "chromedriver.exe");
driver = new ChromeDriver();
break;
case "ie":
System.setProperty("webdriver.ie.driver", drPath + "IEDriverServer.exe");
driver = new InternetExplorerDriver();
break;
case "firefox":
System.setProperty("webdriver.gecko.driver", drPath + "geckodriver.exe");
driver = new FirefoxDriver();
break;
}
System.out.println("\nInvoked browser = " + browser);
return driver;
}
}

DB_Helper

package Helpers;

import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;

public class DB_Helper {

private static final String dbUAT = "jdbc:postgresql://srilu:0000/srilu_uat";
private static final String dbuser = "Srilu";
private static final String dbpass = "password";

private static Connection conn;
private static Statement st;
private static ResultSet rs;
private static String valueString;

private static Connection getDBConn(){
conn = null;

try {
Class.forName("org.postgressql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Not able to load PostgreSQL");
e.printStackTrace();
System.exit(1);
}
try {
conn = DriverManager.getConnection(dbUAT, dbuser, dbpass);
} catch (SQLException e){
System.out.println("Not able to connect to DB");
e.printStackTrace();
System.exit(1);
}
return conn;
}

public static String fromColumn_GetString(String query, String column) throws SQLException {
try {
st = getDBConn().createStatement();
rs = st.executeQuery(query);
while (rs.next())
valueString = rs.getString(column);
} catch (SQLException e) {
System.out.println("\n" + " Column does not exist. From Query - " + query);
e.printStackTrace();
}
return valueString;
}

public static void del_fromTable(String query) throws SQLException {
try {
st = getDBConn().createStatement();
st.executeQuery(query);
} catch (SQLException e) {
System.out.println("\n Table does not exist to delete");
e.printStackTrace();
}
}

public static void closeDB() throws SQLException {
conn.close();
}

}

Env_Helper

package Helpers;

public class Env_Help {

private static String env;
private static String portal;

public static String getBaseURL(String portal) throws Throwable {
return chooseURL(portal);
}

public static String chooseEnv(){

env = System.getProperty("ENV");

if (env == null){
env = System.getenv("ENV");
if (env == null){
env = "PROD";
}
}
return env;
}

public static String choosePortal() {

env = System.getProperty("MP");

if(env == null){
env = System.getenv("MP");
if (env == null) {
env = "US";
}
}
return env;
}



private static String chooseURL(String portal) throws Throwable {
switch (chooseEnv())
{
case "prod": env = "https://google." + portal; break;
case "uat": env = "https://uat.google." + portal; break;
case "qa": env = "https://qa.google." + portal;
}
return env;
}

static String portal() throws Throwable {
switch (choosePortal())
{
case "AUSTRALIA" : portal = "co.au"; break;
case "INDIA" : portal = "co.in"; break;
case "US" : portal = "com";

}
return portal;
}
}



FilePath

package Helpers;

import java.util.Date;

public class FilePath {

// //Folder Locations
public static final String projectLocation = "C:\\Users\\your\\space\\Auto_Sri\\";
public static final String fromLocation = projectLocation +"src\\data\\";

public static Date d = new Date();
public static String date = d.toString().substring(0, 10);
public static final String toLocation = projectLocation + "src\\testResults\\" + date + "\\";

// // ScreenShots logged here
public static final String screenShots = toLocation;
public static final String logFile = toLocation;
}


Time_Helper

package helpers;

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;

public class Time_Helper {

static WebDriver driver;

public static void minutes(int i)
{
driver.manage().timeouts().implicitlyWait(i, TimeUnit.MINUTES);
}

public static void seconds(int i)
{
driver.manage().timeouts().implicitlyWait(i, TimeUnit.SECONDS);
}
}


Screenshot_Helper

package Helpers;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.support.ui.Wait;

import static Helpers.Browser_Helper.getDriver;


public class Screenshot {

private static WebDriver driver = getDriver();
private static File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

static Wait<WebDriver> wait;


public static void Page(String fileName) throws IOException {

FileHandler.copy(srcFile, new File(FilePath.screenShots + fileName + ".jpg"));
System.out.println("Image Posted = " + FilePath.screenShots + fileName + ".jpg");
}

public static void Element(WebElement element, String fileName) throws IOException {

try{
driver = new Augmenter().augment(driver);
}catch (Exception ignored){

}

Point one = element.getLocation();
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
Rectangle square = new Rectangle (width, height);

BufferedImage img = null;
img = ImageIO.read(srcFile);

BufferedImage pic = img.getSubimage(one.getX(), one.getY(), square.width, square.height);
ImageIO.write(pic, "png", srcFile);

FileHandler.copy(srcFile, new File(FilePath.screenShots + fileName + ".jpg"));
System.out.println("Image Posted = " + FilePath.screenShots + fileName + ".jpg");

}

}

Excel_Helper

package Helpers;

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;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Excel_Helper {

private static XSSFSheet Sheet;
private static XSSFWorkbook WorkBook;
private static XSSFCell Column;
private static XSSFRow Row;
public static FileInputStream ExcelIn;
public static FileOutputStream ExcelOut;


private static final String fromDataLoc = "";

// // Get Excel File and the tab
public static void fromExcel(String book, String tab) throws Exception {
try {
String location = (fromDataLoc + book + ".xlsx");
ExcelIn = new FileInputStream(location);
WorkBook = new XSSFWorkbook(ExcelIn);
Sheet = WorkBook.getSheet(tab);

System.out.println("Excel File Used from = " + location);
System.out.println("Excel SHEET used = " + tab);

} catch (Exception e){
throw (e);
}
}

public static String fromColumn (int Ro, int Col) throws Exception {

try {
Column = Sheet.getRow(Ro).getCell(Col);
String data = Column.getStringCellValue();
return data;
} catch (Exception e) {
return "";
}
}

public static void toExcelSheet(String tab) throws Exception{

try {
WorkBook = new XSSFWorkbook();
Sheet = WorkBook.createSheet(tab);
Row = Sheet.createRow(0);
System.out.println("Excel SHEET created = " + tab);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void toColumn(String text, int col) throws Exception{

try{
int count = Sheet.getLastRowNum();
Row = Sheet.createRow(count+1);
Column = Row.createCell(col);
Column.setCellValue(text);
} catch (Exception e){
throw (e);
}
}

public static void saveToExcel(String book) throws Exception{

try{
String location = (fromDataLoc + book + ".xlsx");
ExcelOut = new FileOutputStream(location);
WorkBook.write(ExcelOut);

ExcelOut.close();
System.out.println("Excel File Written to = " + location);

} catch (Exception e){
throw (e);

}
}

public static void closeExcel() throws IOException {
WorkBook.close();
}

}

Comments

Popular posts from this blog

A Testers Life

Lots of Work

Vanilla Ice Cream caused General motors to not start