Total Pageviews

Friday 19 September 2014

Selenium Mobile Automation

https://code.google.com/p/selenium/wiki/AndroidDriver

http://manojhans.blogspot.in/2013/08/native-android-apps-automation-with.html

How to scroll web element?--not browser—



FirefoxProfile profile=new FirefoxProfile();
profile.setEnableNativeEvents(true);
WebDriver driver=new FirefoxDriver(profile);
driver.navigate("http://jqueryui.com/draggable/");
Thread.sleep(6000L);
WebElement element=driver.findElement(By.xpath("//div[@id='draggable']"));
Actions actn=new Actions(driver);
actn.dragAndDropBy(element, 50, 50).build().perform();

How to refresh a page without using context click?

1.Using sendKeys.Keys method
driver.get("https://accounts.google.com/SignUp");
driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);
2.Using navigate.refresh() method
driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/100-selenium-interview-questions.html");
driver.navigate().refresh();
3.Using navigate.to() method
driver.get("http://ruchi-myseleniumblog.blogspot.in/2014/01/selenium-hybrid-framework-using.html");
driver.navigate().to(driver.getCurrentUrl());
4.Using get() method
driver.get("http://ruchi-myseleniumblog.blogspot.in/2013/12/basic-core-java-interview-questions.html");
driver.get(driver.getCurrentUrl());
5.Using sendKeys() method
driver.get("https://accounts.google.com/SignUp");

driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");

Database Connection using Java and Selenium

Database Connection using Java and Selenium

// import sql package
import java.sql.*;

//http://docsrv.sco.com/JDK_guide/jdbc/getstart/callablestatement.doc.html
public class Database_connection {


public static void main(String[] args) throws SQLException {

 Connection conn = null;
 String url = "jdbc:mysql://localhost:3306/";
 String dbName = "test";
 String driver = "com.mysql.jdbc.Driver";
 String userName = "root";
 String password = "root";

 try{
 Class.forName(driver).newInstance();// create object of Driver
 conn = DriverManager.getConnection(url+dbName,userName,password);
 // connection will be established

 // *******************Statement******************
 Statement stmt = conn.createStatement();
 ResultSet rs = stmt.executeQuery("select * from users");

//  rs.next(); // 1st row
//  System.out.println(rs.getString(2));
//  rs.next(); // 2nd row
//  System.out.println(rs.getString(1));
 while(rs.next()){
System.out.println(rs.getString(1) + "-- "+rs.getString(2)+" -- "+rs.getString(3));
 }

 System.out.println("*********************************");
 // *****************PREPARED STATEMENT**************
 PreparedStatement pstmt = conn.prepareStatement("select * from users where name = ? and sex=?");
 pstmt.setString(1, "B");
 pstmt.setString(2, "F");
 ResultSet rs1 = pstmt.executeQuery();

 while(rs1.next()){
System.out.println(rs1.getString(1) + "-- "+rs1.getString(2)+" -- "+rs1.getString(3));
 }


//***************Callable Statement************************
 //CallableStatement cstmt = conn.prepareCall("{call getTestData(?,?,?,?)}");
   //cstmt.registerOutParameter(1, java.sql.Types.DECIMAL, 3);
   //cstmt.setString(2, "xxxxx");
 
 
   //cstmt.executeUpdate();
  // double d =cstmt.getDouble(1);

//     //********************Add row Insert************************
   pstmt = conn.prepareStatement("insert into users values (?,?,?)");
   pstmt.setString(1, "Tom");
   pstmt.setString(2, "London");
   pstmt.setString(3, "M");
 
   int i=pstmt.executeUpdate();
   if(i==1){
    System.out.println("inserted the record");
   }
 

 }catch(Exception e){
  e.printStackTrace();
 }finally{
 conn.close();
 }
}

}

java program to count number of unique words separated by comma (,) or newline and their occurrence from text file.

java program to count number of unique words separated by comma (,) or newline and their occurrence from text file.


package programs;

import java.util.*;
import java.io.*;

public class uniquewrdsoccurence {

private String[] spliter;
private int[] count;
public void countWord(String Text) {

String temp1 = Text.replaceAll("[\\n]", " ");
String temp = temp1.replaceAll(",", " ");
spliter = temp.replaceAll("[.?!:;/]", "").split(" ");
count = new int[spliter.length];
for (int i = 0; i < spliter.length; i++) {
temp = spliter[i];
for (int k = 0; k < spliter.length; k++) {
if (temp.equalsIgnoreCase(spliter[k])) {
count[k]++;
}
}
}

printResult();
}

private void printResult() {

HashMap map = new HashMap();
int counter = 0;

for (int i = 0; i < spliter.length; i++) {
map.put(spliter[i].toLowerCase(), count[i]);
}

Iterator it = map.keySet().iterator();

System.out.println("Words             Count");
System.out.println("#######################");
while (it.hasNext()) {
counter++;

String temp = (String) it.next();

// prints the word 
System.out.print(temp);

// prints the spaces
for (int i = 0; i < (20 - temp.length()); i++) {
System.out.print(" ");
}

// print the value -total count
System.out.println(map.get(temp.toString()));

}
System.out.println("#######################");
System.out.println("Number of unique words in file:" + counter);
}

// main method 
public static void main(String[] arg) {
String pattern = "";
String str = null;

try {
FileInputStream filestream = new FileInputStream(
System.getProperty("user.dir") + "\\words.txt");
DataInputStream datastream = new DataInputStream(filestream);
BufferedReader Br = new BufferedReader(new InputStreamReader(datastream));
while ((str = Br.readLine()) != null) {
pattern = pattern.concat(str);
pattern = pattern.concat(" ");
}
datastream.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
uniquewrdsoccurence wco = new uniquewrdsoccurence();
wco.countWord(pattern);
}

}

How to find broken images in a page using Selenium

How to find broken images in a page using Selenium

package programs;

import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class findbrokenimages {
static int invalidimg;
static WebDriver driver ;
public static void main(String[] args) {
try {
driver = new FirefoxDriver();
driver.get("http://ruchi-myseleniumblog.blogspot.in");
invalidimg = 0;
List allImages  = driver.findElements(By.tagName("img"));
System.out.println("Total  images are " + allImages.size());
for (int i = 0; i < allImages.size(); i++) {
WebElement img = (WebElement) allImages.get(i);
if (img != null) {
verifyimgActive(img);
}
}

System.out.println("Total invalid images are " + invalidimg);
driver.quit();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}



public static void verifyimgActive(WebElement img) {
try {
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(img.getAttribute("src")));
   if (response.getStatusLine().getStatusCode() != 200)
invalidimg++;
}
catch (Exception e) {
e.printStackTrace();
}
}
}

Read XML file using java

Java Program to read or.xml file
package programs;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ORxml {
    public static void main(String arg[]) {
        try {
            File inputfile = new File(System.getProperty("user.dir")
                    + "\\OR.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docbuilder = dbFactory.newDocumentBuilder();
            Document doc = docbuilder.parse(inputfile);
            doc.getDocumentElement().normalize();
            System.out.println("Root element :"
                    + doc.getDocumentElement().getNodeName());
            NodeList nodelist = doc.getElementsByTagName("Object");
            System.out.println("##################################");
            for (int tmp = 0; tmp < nodelist.getLength(); tmp++) {
                Node nNode = nodelist.item(tmp);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    System.out.println("object name : "
                            + eElement.getAttribute("name"));
                    System.out.println("propertytype : "
                            + eElement.getElementsByTagName("propertytype")
                            .item(0).getTextContent());
                    System.out.println("propertyvalue: "
                            + eElement.getElementsByTagName("propertyvalue")
                            .item(0).getTextContent());
                    System.out.println("--------------------------------------");
                }
            }
        } catch (Exception e) {
            e.getMessage();
            e.printStackTrace();
        }
    }

}

Database Connection using Java and Selenium

Database Connection using Java and Selenium

// import sql package
import java.sql.*;

//http://docsrv.sco.com/JDK_guide/jdbc/getstart/callablestatement.doc.html
public class Database_connection {


public static void main(String[] args) throws SQLException {

 Connection conn = null;
 String url = "jdbc:mysql://localhost:3306/";
 String dbName = "test";
 String driver = "com.mysql.jdbc.Driver";
 String userName = "root";
 String password = "root";

 try{
 Class.forName(driver).newInstance();// create object of Driver
 conn = DriverManager.getConnection(url+dbName,userName,password);
 // connection will be established

 // *******************Statement******************
 Statement stmt = conn.createStatement();
 ResultSet rs = stmt.executeQuery("select * from users");

//  rs.next(); // 1st row
//  System.out.println(rs.getString(2));
//  rs.next(); // 2nd row
//  System.out.println(rs.getString(1));
 while(rs.next()){
System.out.println(rs.getString(1) + "-- "+rs.getString(2)+" -- "+rs.getString(3));
 }

 System.out.println("*********************************");
 // *****************PREPARED STATEMENT**************
 PreparedStatement pstmt = conn.prepareStatement("select * from users where name = ? and sex=?");
 pstmt.setString(1, "B");
 pstmt.setString(2, "F");
 ResultSet rs1 = pstmt.executeQuery();

 while(rs1.next()){
System.out.println(rs1.getString(1) + "-- "+rs1.getString(2)+" -- "+rs1.getString(3));
 }


//***************Callable Statement************************
 //CallableStatement cstmt = conn.prepareCall("{call getTestData(?,?,?,?)}");
   //cstmt.registerOutParameter(1, java.sql.Types.DECIMAL, 3);
   //cstmt.setString(2, "xxxxx");
 
 
   //cstmt.executeUpdate();
  // double d =cstmt.getDouble(1);

//     //********************Add row Insert************************
   pstmt = conn.prepareStatement("insert into users values (?,?,?)");
   pstmt.setString(1, "Tom");
   pstmt.setString(2, "London");
   pstmt.setString(3, "M");
 
   int i=pstmt.executeUpdate();
   if(i==1){
    System.out.println("inserted the record");
   }
 

 }catch(Exception e){
  e.printStackTrace();
 }finally{
 conn.close();
 }
}

}

happy learning...

Comparing 2 images in java-Selenium

Here is a function to Compare two images in JAVA.


import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
import java.io.File;

public static String processImage() {
System.out.println("Executing processImage Keyword");

try {

String file1 = "D:\\Images\\images.JPEG";
String file2 = "D:\\Images\\images2.JPEG";

Image pic1= Toolkit.getDefaultToolkit().getImage(file1);
Image pic2= Toolkit.getDefaultToolkit().getImage(file2);

try {

PixelGrabber grab11 = new PixelGrabber(pic1, 0, 0, -1, -1,
false);
PixelGrabber grab21 = new PixelGrabber(pic2, 0, 0, -1, -1,
false);

int[] array1= null;

if (grab11.grabPixels()) {
int width = grab11.getWidth();
int height = grab11.getHeight();
array1= new int[width * height];
array1= (int[]) grab11.getPixels();
}

int[] array2 = null;

if (grab21.grabPixels()) {
int width = grab21.getWidth();
int height = grab21.getHeight();
array2 = new int[width * height];
array2 = (int[]) grab21.getPixels();
}

System.out.println("Pixels equal: "
+ java.util.Arrays.equals(array1, array2 ));

} catch (InterruptedException e1) {
e1.printStackTrace();
}
return "Pass";
} catch (Throwable t) {
// report error
return "Fail - " + t.getMessage();
}

}

Web Site URL 's for selenium informaiton.....

1. http://www.studyselenium.com/

2.http://automationtricks.blogspot.in/

visit these blogsposts for more informaiton.....

Wednesday 10 September 2014

How to take a screenshot in selenium webdriver

Topic: How to take a screenshot in selenium web driver


Code: i have implemented in TestNG method

 @Test
  public void takeScreenShotTest() throws IOException
  {
 WebDriver driver=new FirefoxDriver();
driver.get("https://google.co.in");
File scrFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\Users\\Dell\\Desktop\\GoogleScreenShot.jpg"));
  }


output:

How To record the Test Execution as a video

Topic: How to record the Test Execution as a .mov file

steps: we just have to add 3 lines of code for

1. Setting up a recorder

2. Starting the recorder

3. Stopping the recorder


code:

ATUTestRecorder recorder = new ATUTestRecorder("Directory","filename",false);

recorder.start();

WebDriver browser = new FirefoxDriver();

browser.navigate().to("http://www.w3schools.com/ajax/ajax_database.asp");

browser.manage().window().maximize();

browser.quit();

recorder.stop();





Precondition:    Import the .JAR file and add to Eclipse

download link: https://drive.google.com/folderview?id=0B7rZvkq9tkwPUHRXNU8wQjRYVDA&usp=sharing&tid=0B7rZvkq9tkwPRy1HLVJCdWtNekE
procedure:
Right click on project -- Build Path -- >  configure Build Path ---- > Libraries  -----> Click on "Add external jars " --- > select ATUTestrecorder.jar fille -----> click on "ok"


HAPPY RECORDING......





How to read xml file using java.

Example XML fiile shown bellow.

<class> //It is root element

<student rollno='001'>
<firstname>Parimi</firstname>
<lastname>satish</lastname>
<nickname>pandu</nickname>
</student>

<student rollno='002'>
<firstname>maha</firstname>
<lastname>madi</lastname>
<nickname>dinga</nickname>
</student>

</class>



----------------------------------------------------------------------------------------------------------------------
use the bellow code, and change the file path..

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ReadCustomXMLFile
{

public static void main(String [] args)
{
try
{
File fXmlFile = new File("E:\\tutorials\\Selenium Videos\\xml filehandling\\testdata.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

//To get Root element i.e class  ---- in testda.xml file
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());


// get no of sub - nodes i.e "student" nodes in the xml file
NodeList nList = doc.getElementsByTagName("student");
System.out.println(nList.getLength());


//get all the attribute values in the both sub nodes...

for(int temp=0;temp<=nList.getLength();temp++)
{

//to Get all sub-nodes names use bello code....
Node nNode = nList.item(temp);
System.out.println("Sub Node Name is :  "+nNode.getNodeName());


//

if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;


//to get roll no of the  student
System.out.println("Student ID is :"+eElement.getAttribute("rollno"));


//to get firstname of the student
System.out.println("First Name is: "+eElement.getElementsByTagName("firstname").item(0).getTextContent());

//To get Last name of the Student
System.out.println("Last Name is :"+eElement.getElementsByTagName("lastname").item(0).getTextContent());

//To get Nick Name of the Student is
System.out.println("Nick Name is :"+eElement.getElementsByTagName("nickname").item(0).getTextContent());

}

}

}
catch (Exception e)
{
e.printStackTrace();
}

}
}

Friday 5 September 2014

Wait Staments - Fluent Wait

Sample usage:

  • Each FluentWait instance defines the maximum amount of time to wait for a condition,
  •  As well as the frequency with which to check the condition.
  •  Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
Syntax to use in real time Project:

// Waiting 30 seconds for an element to be present on the page, checking
   // for its presence once every 5 seconds.
   Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

   WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
     public WebElement apply(WebDriver driver) {
       return driver.findElement(By.id("foo"));
     }
   });


------------------------------------------------------------

Methods in  Detail

withTimeout :Sets how long to wait for the evaluated condition to be true. The default timeout is FIVE_HUNDRED_MILLIS

pollingEvery: Sets how often the condition should be evaluated.

In reality, the interval may be greater as the cost of actually evaluating a condition function is not factored in. The default polling interval is FIVE_HUNDRED_MILLIS.
  • ignoreAll

    public <K extends java.lang.Throwable> FluentWait<T> ignoreAll(java.util.Collection<java.lang.Class<? extends K>> types)
    Configures this instance to ignore specific types of exceptions while waiting for a condition. Any exceptions not whitelisted will be allowed to propagate, terminating the wait.
    Parameters:
    types - The types of exceptions to ignore.
    Returns:
    A self reference.
  • ignoring

    public FluentWait<T> ignoring(java.lang.Class<? extends java.lang.Throwable> firstType,
       java.lang.Class<? extends java.lang.Throwable> secondType)
    See Also:
    ignoreAll(Collection)
  • until

    public void until(com.google.common.base.Predicate<T> isTrue)
    Repeatedly applies this instance's input value to the given predicate until the timeout expires or the predicate evaluates to true.
    Parameters:
    isTrue - The predicate to wait on.
    Throws:
    TimeoutException - If the timeout expires.
  • timeoutException

    protected java.lang.RuntimeException timeoutException(java.lang.String message,
                                              java.lang.Throwable lastException)
    Throws a timeout exception. This method may be overridden to throw an exception that is idiomatic for a particular test infrastructure, such as an AssertionError in JUnit4.
    Parameters:
    message - The timeout message.
    lastException - The last exception to be thrown and subsequently suppressed while waiting on a function.
    Returns:
    Nothing will ever be returned; this return type is only specified as a convenience.

Tuesday 2 September 2014

How to launch the fire fox browser with firebug

Topic: How to launch the fire fox browser with firebug

step1 :you saved Firebug XPI into the C:\FF_Profile folder
step2 :as firebug.xpi (go to Firebug download page, right-click on the "Download Now "
step 3:save as C:\FF_Profile\firebug.xpi

then run the bello code.. in java class.........

final String firebugPath = "C:\\FF_Profile\\firebug.xpi";
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File(firebugPath));
WebDriver driver = new FirefoxDriver(profile);
driver.get("http://ftindia.com/");