Wednesday 27 November 2013

Window (File Upload/Download) in Selenium webdriver


File Upload/Download using Autoit
I would like to explain the Autoit tool on the file upload functionality. Download the tool from http://www.autoitscript.com/site/autoit/downloads/ , create the appropriate Autoit .au3 script, compile into exe file, test the exe file to verify whether the functionality is working as expected and integrate with selenium. Read the help file for better understanding.
Scenario:
I have web button on the page, when selected; browser opens the following window (attaching screen shot below). Selenium works fine till Browse button selection, now it is the responsibility of the Autoit script to upload the file so that selenium can continue with the remaining GUI activity.



Steps:
1. Select the File Upload window. Drag and drop the finder tool icon on the windows objects to get its corresponding properties following screen shot demonstrates how to open and capture the windows controls.











2. Open Script Editor (program files), write the code for ex.



AutoIt Script
WinWaitActive("File Upload")
Send("D:\demo.txt")
ControlClick("", "&Open", "Button1")



3. Save the file as demo.au3
4. Right click on this file and click ‘Compile Script’. This will create a demo.exe file at the same location.
5. Select open button, so that all the selection details are transferred into web page control and selenium can take control of the next activity.

Autoitdemo.java

public class Autoitdemo {
         
          public static void main(String[] args)  {
                   try{            
                  
                   WebDriver driver = new FirefoxDriver();
                   driver.get("http://www.sendspace.com/");
System.out.println(" Page Opened is: "+driver.getCurrentUrl()+"\n"+driver.getTitle() );
                   driver.findElement(By.xpath("//*[@id='upload_file']")).click();
                   System.out.println(" Browse button clicked");
                   Runtime.getRuntime().exec("D:\\demo1.exe"); //call Autoit script
                   System.out.println(" Execution Finished ");
                   driver.close();
                    }catch(Exception e)
                    {       
e.printStackTrace();
                   System.out.println(e.getMessage());    
                  
          }
          }
}

Java Code to call Autoit Script
Runtime.getRuntime().exec("D:\\demo1.exe");

For more help go to:




Flex Testing using Selenium Webdriver

To Test Flex Applications Create Package {e.g. testscript } .Copy below 2 files in it.Right Click Youtube.java and Select Run As Java Application.

//FlexWebDriver.java
package testscript;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;

public class Flextesting {
    private final WebDriver webDriver;
   private final String flshObjectId;

    public FlexWebDriver(final WebDriver webDriver, final String flshObjectId) {
        this.webDriver = webDriver;
        this.flshObjectId = flshObjectId;
    }

    public String click(final String objectId, final String optionalButtonLabel) {
        return call("doFlexClick", objectId, optionalButtonLabel);
   }

    public String click(final String objectId) {
         return click(objectId, "");
    }

//... Omitted for clarity ...

    public String call(final String functionName, final String... args) {
      final Object result =
            ((JavascriptExecutor)webDriver).executeScript(
                 makeJsFunction(functionName, args),
                 new Object[0]);

         return result != null ? result.toString() : null;
    }

    private String makeJsFunction(final String functionName, final String... args) {
         final StringBuffer functionArgs = new StringBuffer();

        if (args.length > 0) {
            for (int j = 0; j < args.length;j++) {
                if (j > 0) {
                    functionArgs.append(",");
            }
                functionArgs.append(String.format("'%1$s'", args[j]));
         }
        }
        return String.format(
            "return document.%1$s.%2$s(%3$s);",
            flshObjectId,
            functionName,
            functionArgs);
    }
}

//Youtube .java

package testscript;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;


public class Youtube {

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

System.setProperty("webdriver.ie.driver",System.getProperty("user.dir")+ "\\IEdriver\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
 Flextesting flashApp = new Flextesting(driver, "movie_player");

driver.get("http://www.youtube.com/watch?v=qdf5NofgGfU&feature=fvst");
System.out.println(" Page Opened is: "+driver.getCurrentUrl()+driver.getTitle() );
Thread.sleep(2000L);
    // let the video load
    while (Integer.parseInt(flashApp.call("getPlayerState")) == 3){
    Thread.sleep(1000);
    }
   
    // Play the video for 10 seconds
    Thread.sleep(5000);
    flashApp.call("pauseVideo");
    System.out.println(" Executing pauseVideo  function ");    
    Thread.sleep(5000);
    flashApp.call("playVideo");
    System.out.println(" Executing playVideo  function ");
    Thread.sleep(5000);
    flashApp.call("seekTo","140","true");
    System.out.println(" Executing seekTo 140  function ");
    Thread.sleep(5000);
    flashApp.call("mute");
    System.out.println(" Executing mute audio  function ");
    Thread.sleep(5000);
    flashApp.call("setVolume","50");
    System.out.println(" Executing setVolume to 50  function ");
    Thread.sleep(5000);
    System.out.println(" Closing Browser");
    driver.close();
}
             
}



For More Details Go To:
//http://code.google.com/apis/youtube/flash_api_reference.html#playVideo

Friday 22 November 2013

Search in PDf using Java and Itext jar |Selenium Webdriver

Search in Pdf  Store At system using Java in Selenium

Jars Used:

itextpdf-5.1.0.jar

Java Code:
 
String texttosearch="Account";
boolean searchResult=false;
PdfReader reader =new PdfReader("C:\\ruchi\\A1.pdf");
PdfReaderContentParser parser= new PdfReaderContentParser(reader);
TextExtractionStrategy strategy;
for(int i=1;i<=reader.getNumberOfPages();i++);
{
strategy =parser.processContent(i,new SimpleTextExtractionStrategy());
if(strategy.getResultantText().indexOf(textToSearch)>-1)
{
searchResult= true;
break;
}
}
if(searchResult)
{
System.out.println("Search SuccessFull!!!");
}
else
{
 System.out.println("Search SuccessFull!!!");
}


Handling Alert Boxes Using AutoIT in Selenium

Handling alert box using AutoIT

AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying “runtimes” required!.

Here we are going to use AutoIT for handling authentication boxes like below,



Step 1: 

Download the latest version of AutoIT from http://www.autoitscript.com/site/autoit/downloads/
 

Step 2: 

Write the code and Save it as 'Authentication.au3' 
(au3 is the AutoIT format)



Use the below code
WinWaitActive("Authentication Required")
Send("Username")
Send("{TAB}")
Send("Password")
Send("{ENTER}")

Step 3:

After that, right click on your Authentication.au3 file and click 'Compile Script'
This will covert your AutoIT script into an executable file

Step 4:

Now go to your Selenium code, and add the below line.

Runtime.getRuntime().exec("C://Path//Authentication.exe");

Friday 8 November 2013

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();
 }
}

}