Sunday, June 29, 2014

Selenium : Read ,Write and Edit Excel Sheet (Spread Sheet)

Excel Selenium : Read ,Write and Edit Excel Sheet (Spreadsheet)-- Final

Download the latest binary zip file below link and jars into your project
http://poi.apache.org/download.html


Code below(unlike jxl this should work for both xls and xlsx files) :

Workbook wb = WorkbookFactory.create(new FileInputStream("C:\\Users\\DPK\\Desktop\\test.xls"));
Sheet sheet = wb.getSheet("Sheet1");

System.out.println(sheet.getRow(0).getCell(0).getRichStringCellValue()); // Read Cell
sheet.createRow(1).createCell(1).setCellValue(1212); //---Write into a new cell
sheet.getRow(0).getCell(0).setCellValue("333"); //----Edit existing Cell
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\DPK\\Desktop\\test.xls");
wb.write(fileOut);
fileOut.close();
System.out.print("ok");

Saturday, June 28, 2014

Selenium :Headless Browser testing using HtmlUnitDriver and PhantomJS inWebdriver



Headless Browser testing using HtmlUnitDriver and PhantomJS inWebdriver

Headless Browser is a Web Browser without a GUI (Graphical User Interface). It access Web Pages but doesn't show them to any human being. Headless Browser should be able to parse JavaScript.

Html Unit Driver:

HtmlUnitDriver driver = new HtmlUnitDriver();
driver.setJavascriptEnabled(true); //to enable Javascript

To emulate a specific browser :

                   HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3);
 
The other uses a broader capabilities mechanism: 

                   HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);
 
 

PhantomJS

PhantomJS is a Headless Webkit with JavaScript API. PhantomJS is an optimal solution for Headless Website Testing, Screen Capture, Access and manipulate webpages with the standard DOM API, or with usual libraries like jQuery, Network Monitoring PhantomJS comes with in-built GhostDriver.

Note : PhantomJS is not a Test framework, it is used only to LAUNCH the tests via a suitable Test Runner(GhostDriver) for webdriver.


Configure PhantomJS :
1.     PhantomJSDriver-1.0.x.jar can also be downloaded and configured in Eclipse manually.
2.     Add the following imports to your code:

import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;


3. Replace the object, "driver" specifying "FirefoxDriver" with "PhantomJSDriver".
4. Use
WebDriver driver = new PhantomJSDriver();

5. Run Test.

Note:
You can also do the following:
1. Download phantomjs.exe
2. Extract the phantomjs-1.8.x-windows.zip folder and locate phantomjs.exe file to C: / folder
-use the following code instead of the above:

DesiredCapabilities ph_cap = new DesiredCapabilities();
ph_cap.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:/phantomjs.exe");
WebDriver driver = new PhantomJSDriver(ph_cap);

PhantomJS | Screen Capture

DesiredCapabilities ph_cap  = new DesiredCapabilities();
ph_cap.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C://phantomjs.exe");
ph_cap .setCapability("takesScreenshot", true);
driver = new PhantomJSDriver(ph_cap );  
baseUrl = "http://www.xyz.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);


@Test
public void test01() throws Exception {

driver.get(baseUrl + "/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\sample.jpeg"),true);
 

}


Sources :


Tuesday, June 17, 2014

Selenium : WebDriver’s most popular / Basic Commands(important)


WebDriver’s most basic popular Commands
Sample :
https://www.cs.tut.fi/~jkorpela/www/testel.html
http://catchbug.blogspot.in/2014/08/basic-html.html
http://www.ironspider.ca/forms/checkradio.htm


Selenium important code snippets 




Element
Related
Handling parents
Misc Operations
Browsers
Special
File
operations
Framework
Is present
Window
Wait
Chrome
Action
Excel
stringutils.mid
build.gradle
Locators -8
Frame
Navigate
IE
Robot
TextFile
stringutils.indexof
testng.xml
Checkbox
Alert Box
keypress
Cookie
Javascript
screenshot
stringutils.leftpad
dataprovider
Radio





getcapabilities
POM (By)
Dropdown





desriedcapabilities
Softassert
tooltip









Search elements:
1. Try{
a. Driver.findElement(By.xpath(//dd/dd”)).click();
}catch(Exception e){System.out.print(“not present”);

2. If ( Driver.getpagesource().contains(“google search”) == true)

Locators:
1. Xpath
2. Css
3. Linktext
4. Id
5. Name
6. Partiallinktext
7. Tagname
8. ClassName

CheckBox
List<WebElement> eBoxes=driver.FindElements(By.xpath(//input[@type=’checkbox’]”));
For(int i=0;i<=eBoxes.size-1;i++) //for(WebElement w:eBoxes)
eBoxes.get(i).click(); //w.click();

/* Good to know : There is no difference between List and ArrayList in Java
List is a primitive and ArrayList is overrides List in Java*/


RadioButton
List<WebElement> eBoxes=driver.FindElements(By.xpath(//input[@type=’radio’]”));
For(int i=0;i<=eBoxes.size-1;i++) //for(Iterator i=eBoxes;eBoxes.hasnext())
System.out.println(eBoxes.get(i).getattribute(“value”)); // (WebElement)(i . next()). getattribute("value");

Drop Down
1. Select s=new Select(driver.FindElement(By.Xpath("//df/sd")));
s.selectByVisibleText("text here"); //s.selectAll , s.deselectall , s.selectbyIndex
List<WebElement> values=s.getOptions(); //Retrieves all values to list
//LOOPING THROUGH EACH
for(WebElement w:values) // for(Iterator i=values.iterator() ;i.hasnext())
sop(w.getAttribute("value"); // WebElement w=(WebElement)i.next();


2. driver.findElement(By.xpath(“dropdown”)).click();
driver.findElement(By.xpath(“dropdown”)).sendkeys(“abcd”);
driver.findElement(By.xpath(“dropdown”)).click();

Tooltip
System.out.println(driver.findelement(By.Xpath(//body/br”)).getattribute(“title”);

KeyPress:
Driver.findElement(By.Xpath(//body/”)).Sendkeys(“abcd”);
-------------------------------------------------------------------------------------------------------

Handle Windows :
Set<String> winids = driver.getWindowHandles(); \\ Collections =Sets(no duplicates), Map(dictionary),List(ArrayList)
System.out.println(winids.toString()); //prints all window ids
driver.switchTo().window(winids.iterator().next()).close();

Handle Frames
driver.switchTo().frame(id or name);
driver.switchTo().frame(By.Xpath());
List<WebElement> frameList=driver.findElements(By.tagName(“iframe”));

Handle Alert Box
Alert a=driver.switchTo().alert();
System.out.println(a.gettext());
a.accept(); //a.dismiss();

-------------------------------------------------------------------------------------------------------
Different Wait
1. WebDriverWait wait = new WebDriverWait(driver,10);//-------------1
wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/name("locator"));

2. Thread.Sleep(1000) //----------2

3. driver.manage.timeouts().implicitlywait(10,Timeunits.seconds;)//----------3
3. driver.manage.timeouts().pageloadtimeout(10,Timeunits.seconds;)

Navigate
1. driver.get(“http://www.google.com“ );
2. driver.navigate().to(“http://www.google.com”);
driver.navigate().forward();
driver.navigate().back();
driver.navigate().refresh();
Cookie:
driver.manage().deleteAllCookies();
-------------------------------------------------------------------------------------------------------
FireFox
Download Gecko Driver and Unzip :https://github.com/mozilla/geckodriver/releases

System.setProperty("webdriver.gecko.driver","extracted path\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
Chrome
System.setProperty("webdriver.chrome.driver","Path of Chrome driver");
WebDriver driver=new ChromeDriver();

IE
System.setProperty("webdriver.ie.driver","Your_Path//IEDriverServer.exe");
WebDriver webdriver = new InternetExplorerDriver();
-------------------------------------------------------------------------------------------------------
Execute Java Script
import org.openqa.selenium.JavascriptExecutor;


1. (JavascriptExecutor)driver.executeScript("mouse_hover"); //html -- <div id=*** mouseonhover=mouse_hover >
2. ((JavascriptExecutor) driver).executeScript("alert('hello world');");
3. ((JavascriptExecutor) driver).executeScript("document.getElementById('gbqfbb').click()");

Actions - Double Click , DragDrop and Mouse Related Operation
Actions a =new Actions(driver);

WebElement e1=driver.findElement(By.xpath(""));
WebElement e2=driver.findElement(By.xpath(""));

a.moveToElement(e1).doubleClick().perform(); \\Double click
a.dragAndDrop(e1, e2).perform(); \\Drag Drop
a.moveToElement(e1).moveByOffset(X, Y).click().perform();\\Mouse Move

Robot - To perform mouse related operation
Point coordinates =driver.findElement(By.xpath("//canvas")).getLocation();
System.out.println("Co-ordinates"+coordinates);
Robot robot = new Robot();
robot.mouseMove(coordinates.getX(),coordinates.getY());
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Screenshot
File f= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(f, new File("c:\\tmp\\screenshot.png"));

DataProvider
@Dataprovider
public Object[][] dp(){Object[][] o=new Object[1][1];
o[0][0]="hi";
o[0][1]=123;
o[1][0]="bye";
o[1]1]=999;
return o;}

@Test(dataprovider="dp") //executed twice with 1st iteration s=hi and i=123 and 2nd iteration s=bye and i=999
public void m(String s,int i){}

Log Error in TestNg report
1)
public class Assert1 {
SoftAssert soft_assert=new SoftAssert();
@Test
public void test1(){
Assert.assertEquals("abc", "ABC");
Reporter.log("Pass");
System.out.println("hi");
}
@Test
public void test2(){
soft_assert.assertEquals("abc", "ABC");
Reporter.log("fail");
System.out.println("bye");
soft_assert.assertAll();
}
}


2)
Class A extends SelenesetestBase
{
String s="";
try{
driver.findelement(By.Xpath()).click();
}catch(Exception.e)
{
s=e.getmessage();
Reporter.log("element not found <br>");
}

if(s.contentequals("")==false)
fail(s);
}

Stringutils.mid (requires apache StringUtils API)
Stringutils.mid(input,start ,number of characters)
EX :Stringutils.mid("ABC",1,2) //output : AB

StringUtils.indexof (requires apache StringUtils API)
StringUtils.indexof(Input,character sequence)
Example : StringUtils.indexof("ABC","B") //output : 2

-------------------------------------------------------------------------------------------------------
Excel (works for both xlsx and xls files .
Also refer "Fast excel" http://catchbug.blogspot.in/2014/10/selenium-fastexcel.html )
import org.apache.poi.ss.usermodel.Workbook; \\poi-3.14.jar
import org.apache.poi.ss.usermodel.WorkbookFactory; \\poi-ooxml-3.14.jar

Workbook wb = WorkbookFactory.create(new FileInputStream("C:\\Users\\DPK\\Desktop\\test.xls"));
Sheet sheet = wb.getSheet("Sheet1");

System.out.println( sheet.getRow(0).getCell(0).getRichStringCellValue() ); // Read Cell
sheet.createRow(1).createCell(1).setCellValue(1212); //---Write into a new cell
sheet.getRow(0).getCell(0).setCellValue("333"); //----Edit existing Cell



System.out.println(sheet.getLastRowNum());
System.out.println(sheet.getRow(0).getLastCellNum());
wb.write(new FileOutputStream("C:\\Users\\DPK\\Desktop\\test.xls"));

Text write File
FileUtils.write(new File("C:\\1.txt"), "hi");

Text ReadFile
String str= FileUtils.readFileToString(new File("C:\\Users\\1.txt")) ;

PropertiesFile
properties p=new properties();
Inputfilestream f=new InputFilestream("C:\\properties_file.properties");
p.load(f);
p.getproperty("excel"); //properties_file.properties :- excel=c:\\1.xls

testng.xml
<suite name="some name">
<test name = "other name">
<parameter name ="var" value="hi"/>
<classes>
<class name = "packagename.class" />
<classes>
</test>
</suite>

build.gradle
apply plugin: 'maven'
apply plugin: 'java'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies {
testCompile'org.testng:testng:6.+'
testCompile 'org.seleniumhq.selenium:selenium-java:2.+'
}

test {
testLogging {
events "passed", "skipped", "failed", "standardError","standardOut" //enable result
}
useTestNG {
suites 'src/testng.xml'
}
}


POM(Page object Model)
class T{
By usn=By.xpath("//*[@name='username']")
By pass=By.xpath("//*[@name='pass']")
By ok=By.xpath("//*[@name='ok']")

@test
public void t1(){
driver.findElement(usn).sendkeys("asas");
driver.findElement(pass).sendkeys("123");
driver.findElement(ok).click();

}
-------------------------------------------------------------------------------------------------------
Misc


1. driver.navigate().refresh();
2. driver.findelement(By.Xpath("Xpath ").getcssvalue("");
3. selenium. Set Speed ("2000")
4. What are desiredcapabilities?ans :enable/disable JS , profile
5. driver.manage().timeunits().pageLoadingtime
6. @Test(priority=4)
7. //*[contains(text(),'b')]
8. FirefoxProfile profile = new FirefoxProfile();
// profile.setPreference("general.useragent.override", "some UA string"); // driver path
profile .addExtension(new File("firebug-1.8.1.xpi")); //addin
// firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup screen
Web Driver driver = new FirefoxDriver(profile);

9. driver.getCapabilities().toString() //Browser name ver


DesiredCapabilities dc = DesiredCapabilities.firefox(); \\Looks like firefox() is a static method in class Desiredcapabilities class
//dc.setCapability(FirefoxDriver.BINARY, new File("path_to_binary").getAbsolutePath());
dc.setJavascriptEnabled(true);
WebDriver driver = new FirefoxDriver(dc);