Monday, January 22, 2018

Reading from XLSx simplified with TestNG-Multi columns

package com.main;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
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 org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ExcelReading {

static File strPath = new File("Mapping_State_Sites.xlsx");
static String strSheetName = "Sheet1";
static XSSFSheet sheet;
static XSSFSheet sheetOther;
static XSSFWorkbook workbook;
static Object[][] rawData;
static XSSFCell cell;
static XSSFRow row;

@Test(dataProvider = "data")
public void test(String agency, String code, String city, String metro) {

System.out.println(agency + ": " + code + ": " + city + ": " + metro);
}

@DataProvider(name = "data")
public Object[][] getTableObject() throws IOException {

sheetOther = DataSheet(strPath, strSheetName);
int totalRows = sheetOther.getLastRowNum();
rawData = new Object[totalRows][4];
for (int i = 0; i < totalRows; i++) {

for (int j = 0; j <= 3; j++) {
// System.out.println("TotalRows: " + "[" + i + "]" + " " + "[" + j +
// "]");
rawData[i][j] = getCellData(strSheetName, (i + 1), j);
// System.out.println(getCellData(strSheetName, (i + 1), j));
}

}
return rawData;
}

public static XSSFSheet DataSheet(File strPath2, String SheetName) {
File file = strPath2;
try {
FileInputStream fis = new FileInputStream(file);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheet(SheetName);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}

return sheet;
}

@SuppressWarnings("deprecation")
public static String getCellData(String Sheet, int row1, int col) {

try {

int index = workbook.getSheetIndex(Sheet);

sheet = workbook.getSheetAt(index);
row = sheet.getRow(row1);
if (row == null)
  return "";

cell = row.getCell(col);
if (cell == null)
  return "";

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
return cell.getStringCellValue();

case Cell.CELL_TYPE_BOOLEAN:
return String.valueOf(cell.getBooleanCellValue());

case Cell.CELL_TYPE_BLANK:
return "";

case Cell.CELL_TYPE_ERROR:
return cell.getStringCellValue();

case Cell.CELL_TYPE_NUMERIC:
return String.valueOf(cell.getNumericCellValue());

default:
return "Cell not found";

}
} catch (Exception e) {
e.printStackTrace();
return "row " + row + " or column " + col + " does not exist in xls";
}

}

}

Friday, January 19, 2018

Bugzilla XML RPC Simplified

After having test execution from automation script, is it a manual task to post bugs? No. We can do with the help of XML-RPC support by bugzilla.

Pre-requisite:
  1. <!-- https://mvnrepository.com/artifact/org.apache.xmlrpc/xmlrpc-client -->
    <dependency>
        <groupId>org.apache.xmlrpc</groupId>
        <artifactId>xmlrpc-client</artifactId>
        <version>3.1.3</version>
    </dependency>
  2. Make sure to use java 1.8+ as have used Base64


Objective: If test becomes failure then need to report a bug.

Code:

HttpClient httpClient = new HttpClient();
XmlRpcClient rpcClient = new XmlRpcClient();
XmlRpcCommonsTransportFactory factory = new XmlRpcCommonsTransportFactory(rpcClient);
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
factory.setHttpClient(httpClient);
rpcClient.setTransportFactory(factory);
config.setServerURL(new URL("http://bugzillaofyours/xmlrpc.cgi"));
rpcClient.setConfig(config);
HashMap<String, String> loginMap = new HashMap<String, String>();
loginMap.put("login", "email id");
loginMap.put("password", "password");
loginMap.put("rememberlogin", "Bugzilla_remember");
// login to bugzilla
Object loginResult = rpcClient.execute("User.login", new Object[] { loginMap });
System.err.println("loginResult=" + loginResult);
System.out.println(loginResult);
// map of the bug data
HashMap<String, String> bugMap = new HashMap<String, String>();

bugMap.put("product", "Test-Auto");
bugMap.put("component", "test");
bugMap.put("summary", "Bug created from groovy script");
bugMap.put("description", "This is text including stacktrace");
bugMap.put("version", "1");
bugMap.put("op_sys", "Linux");
bugMap.put("platform", "PC");
bugMap.put("priority", "Normal");
bugMap.put("severity", "Normal");
bugMap.put("status", "CONFIRMED");
// Having one custom field on adding bug screen.
bugMap.put("cf_functionality", "Test");

// create a bug
Object createResult = rpcClient.execute("Bug.create", new Object[] { bugMap });
System.err.println("createResult = " + createResult);
System.out.println(createResult.toString().replace("{id=", "").replace("}", ""));
String strBugID = createResult.toString().replace("{id=", "").replace("}", "");
if (strBugID.length() > 0) {
String str = encoder("full path/fail.png");
HashMap<String, Object> bugAttachmentMap = new HashMap<String, Object>();
bugAttachmentMap.put("ids", strBugID);
bugAttachmentMap.put("data", str);
bugAttachmentMap.put("file_name", "bug");
bugAttachmentMap.put("summary", "Summary");
bugAttachmentMap.put("content_type", "image/png");

// create attachment
Object bugAttachment = rpcClient.execute("Bug.add_attachment", new Object[] { bugAttachmentMap });
System.err.println("createResult = " + bugAttachment);
System.out.println(bugAttachment);

Monday, January 8, 2018

Cookie Simplified


Cookie


package com.examples;

import java.util.HashMap;
import java.util.Set;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class Cookie_07 {

public static void main(String[] args) {
System.setProperty("webdriver.chromedriver.driver", "chromedriver");
ChromeOptions op = new ChromeOptions();
HashMap<String, Object> pref = new HashMap<>();
pref.put("download.defulat_directory", "/home/nimesh/Desktop");
op.setExperimentalOption("prefs", pref);
WebDriver wd = new ChromeDriver(op);

wd.get("https://vpl.bibliocommons.com/search?display_quantity=25&page=1&q=java&t=keyword");

Set<Cookie> st = wd.manage().getCookies();
for (Cookie ck : st) {
if (ck.getName().contains("language")) {
System.out.println("Domain: " + ck.getDomain());
System.out.println("Name: " + ck.getName());
System.out.println("Path: " + ck.getPath());
System.out.println("Value: " + ck.getValue());
System.out.println("Expires: " + ck.getExpiry());
System.out.println("HTTP only: " + ck.isHttpOnly());
System.out.println("****************");
}
}
Cookie ckk = new Cookie("language", "es-ES");
wd.manage().addCookie(ckk);
Set<Cookie> st1 = wd.manage().getCookies();
for (Cookie ck : st1) {
if (ck.getName().contains("language")) {
System.out.println("Domain: " + ck.getDomain());
System.out.println("Name: " + ck.getName());
System.out.println("Path: " + ck.getPath());
System.out.println("Value: " + ck.getValue());
System.out.println("Expires: " + ck.getExpiry());
System.out.println("HTTP only: " + ck.isHttpOnly());
System.out.println("****************");
}
}
wd.navigate().refresh();

}

}

Event Listner Simplified

package com.examples;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.events.AbstractWebDriverEventListener;

public class Evenlistner_Helper_06 extends AbstractWebDriverEventListener {
public void beforeNavigateTo(String url, WebDriver driver) {
System.out.println("Before navigating to: '" + url + "'");
}

public void afterNavigateTo(String url, WebDriver driver) {
System.out.println("Navigated to:'" + url + "'");
}

public void beforeClickOn(WebElement element, WebDriver driver) {
System.out.println("Trying to click on: " + element.toString());
}

public void afterClickOn(WebElement element, WebDriver driver) {
System.out.println("Clicked on: " + element.toString());
}

public void onException(Throwable error, WebDriver driver) {
System.out.println("Error occurred: " + error);
}

}


package com.examples;

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.support.events.EventFiringWebDriver;

public class EventListener_06 {
private static Evenlistner_Helper_06 eventListner;

private static EventFiringWebDriver driver;

public static void main(String[] args) {
String strKey = "webdriver.chrome.driver";
String value = "chromedriver";
System.setProperty(strKey, value);
WebDriver wdd = new FirefoxDriver();
driver = new EventFiringWebDriver(wdd);
eventListner = new Evenlistner_Helper_06();
driver.register(eventListner);

}

public void joke() {
System.setProperty("Webdriver.chrome.driver", "chromedriver");
WebDriver wd = new ChromeDriver();
driver = new EventFiringWebDriver(wd);
eventListner = new Evenlistner_Helper_06();
driver.register(eventListner);
WebElement we = driver.findElement(By.xpath(".//*[@id='hplogo']"));
JavascriptExecutor js = (driver);
js.executeScript("arguments[0].style.backgroundColor='rgb(0,200,0)'", we);
driver.get("http://google.com");
}

}

Screenshot simplified

package com.examples;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Screenshot_05 {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.setProperty("Webdriver.chrome.driver", "chromedriver");
WebDriver wd = new ChromeDriver();
wd.get("http://google.com");
File fl = ((TakesScreenshot) wd).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(fl, new File("sc.png"));
}

}

Dropdown Simplified

package com.examples;

import java.util.List;

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.support.ui.Select;

public class Dropdown_04 {

public static void main(String[] args) throws InterruptedException {
System.setProperty("Webdriver.chrome.driver", "chromedriver");
WebDriver wd = new ChromeDriver();
int i = 0;

if (i == 0) {
System.out.println("To understand selectByIndex and .getFirstSelectionOption");
wd.get("https://www.computerhope.com/jargon/h/html-select-tag.htm");
WebElement we = wd.findElement(By.xpath(".//*[@id='main-content']/article/select"));
JavascriptExecutor js = ((JavascriptExecutor) wd);
String color = "rgb(0,200,0)";
js.executeScript("arguments[0].style.backgroundColor = '" + color + "'", we);
Thread.sleep(5000);
// Going to select value that falls under index as per
new Select(we).selectByIndex(4);
WebElement we1 = new Select(wd.findElement(By.xpath(".//*[@id='main-content']/article/select")))
    .getFirstSelectedOption();

// Going to print latest value that is selected under drop down
System.out.println(we1.getText());
System.out.println("***End***");
}
System.out.println("To fetch all the values of options only not from optgroup");

List<WebElement> we2 = new Select(wd.findElement(By.xpath(".//*[@id='main-content']/article/select")))
    .getOptions();
for (WebElement w : we2) {
System.out.println(w.getText());
}
System.out.println("***End***");
System.out.println("To set value in drop down \"Tyrannosaurus\"");
wd.findElement(By.xpath(".//*[@id='main-content']/article/select")).sendKeys("Tyrannosaurus");
System.out.println("***End***");
System.out.println("To know total number values available in dropdown");

int k = new Select(wd.findElement(By.xpath(".//*[@id='main-content']/article/select")))
    .getOptions().size();
System.out.println(new Select(wd.findElement(By.xpath(".//*[@id='main-content']/article/select")))
    .getOptions().size());
System.out.println("***End***");
System.out.println(wd.getTitle());
Thread.sleep(5000);
wd.quit();

}

}

Multiple Tags Simplified


package com.examples;

import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Multiple_Tabs_03 {

public static void main(String[] args) throws InterruptedException {
System.setProperty("Webdriver.chrome.driver", "chromedriver");
WebDriver wd = new ChromeDriver();
int i = 2;
if (i == 2) {
wd.get("https://www.w3schools.com/jsref/met_win_open.asp");

wd.findElement(By.xpath(".//*[@id='main']/div[2]/a")).click();
Set<String> str = wd.getWindowHandles();
for (String st : str) {
wd.switchTo().window(st);
System.out.println(wd.getTitle());
Thread.sleep(5000);
wd.close();

}

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(wd.getTitle());
}
}

}

File Download Simplified

package com.examples;

import java.io.File;
import java.util.HashMap;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

public class File_Download_02 {

@SuppressWarnings("boxing")
public static void main(String[] args) {
// System.setProperty("webdriver.chromedriver.driver", "chromedriver");
String downloadFilepath = "/home/nimesh/Desktop";
HashMap<String, Object> chromePrefs = new HashMap<String, Object>();
chromePrefs.put("profile.default_content_settings.popups", 0);
chromePrefs.put("download.default_directory", downloadFilepath);
chromePrefs.put("download.directory_upgrade", true);

DesiredCapabilities capabilities = DesiredCapabilities.chrome();

ChromeDriverService service = new ChromeDriverService.Builder().usingDriverExecutable(new File("chromedriver"))
    .usingAnyFreePort()
    .build();
ChromeOptions options1 = new ChromeOptions();
options1.merge(capabilities);
options1.setExperimentalOption("prefs", chromePrefs);
// ChromeDriver driver = new ChromeDriver(service, options);
WebDriver wd = new ChromeDriver(options1);
int i = 0;
if (i == 0) {
wd.get("http://www.sample-videos.com/download-sample-xls.php");
wd.findElement(By.xpath("html/body/div[4]/div[1]/div[2]/div[2]/table/tbody/tr[1]/td[4]/a")).click();
// wd.findElement(By.xpath("html/body/form/input[2]")).sendKeys("Test");
// wd.findElement(By.xpath("html/body/form/input[3]")).click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(wd.getTitle());
}

}

}

File Upload Simplified


package com.examples;

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;

public class File_Upload_01 {

public static void main(String[] args) {
System.setProperty("Webdriver.chrome.driver", "chromedriver");
WebDriver wd = new ChromeDriver();
int i = 2;
if (i == 0) {
wd.get("http://cgi-lib.berkeley.edu/ex/fup.html");
wd.findElement(By.xpath("html/body/form/input[1]")).sendKeys("/operadriver");
wd.findElement(By.xpath("html/body/form/input[2]")).sendKeys("Test");
wd.findElement(By.xpath("html/body/form/input[3]")).click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(wd.getTitle());
}
if (i == 1) {
wd.get("https://encodable.com/uploaddemo/");
wd.findElement(By.xpath(".//*[@id='uploadname1']")).sendKeys("/operadriver");
wd.findElement(By.xpath(".//*[@id='newsubdir1']")).sendKeys("Test");
wd.findElement(By.xpath(".//*[@id='formfield-email_address']")).sendKeys("Test@test.com");
wd.findElement(By.xpath(".//*[@id='formfield-first_name']")).sendKeys("Test");

wd.findElement(By.xpath(".//*[@id='uploadbutton']")).click();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(wd.getTitle());
}
if (i == 2) {
wd.get("https://www.websupergoo.com/file-upload-1.htm");
wd.findElement(By.xpath(".//*[@id='page-content']/article/section/form/fieldset/input[1]"))
    .sendKeys("/operadriver");
// wd.findElement(By.xpath(".//*[@id='newsubdir1']")).sendKeys("Test");
// wd.findElement(By.xpath(".//*[@id='formfield-email_address']")).sendKeys("Test@test.com");
// wd.findElement(By.xpath(".//*[@id='formfield-first_name']")).sendKeys("Test");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// .click();
/*
* Actions ac = new Actions(wd); ac.click(wd.findElement(By.cssSelector(
* ".container>form>fieldset>input[type='submit']")));
*/
WebElement element = wd.findElement(By.xpath(".//*[@id='page-content']/article/section/form/fieldset/input[2]"));

JavascriptExecutor executor = (JavascriptExecutor) wd;
executor.executeScript("arguments[0].click();", element);
wd.switchTo().alert().dismiss();
System.out.println(wd.getTitle());
}
// wd.quit();

}

}