Saturday 27 April 2013


Selenium RC Interview Questions

Below are the list of interview questions on selenium RC. Post in comments if anyone need answers for any questions.
  1. What version of Selenium RC you are using?
  2. How Selenium RC works at core components level?
  3. What all languages and browsers that Selenium RC supports?
  4. How you start selenium server?
  5. What are different Start modes of Selenium RC?
  6. When to use proxy injection mode?
  7. How you handle SSL or HTTPS using selenium RC?
  8. How to automate Flash based applications?
  9. Explain about your automation framework
  10. How to handle alerts and pop up?
  11. How to handle Modal dialog?
  12. How to handle AJAX components?
  13. How you upload a file?
  14. How you click on scroll bar button in web application?
  15. Which 3rd party tools/add-ons you use for identifying object identifiers?
  16. How you manage object repository?
  17. How to extend selenium RC for user defined functions?
  18. Is it possible to select a text and compare text?
  19. Have you ever automated Localization test cases using selenium RC?
  20. Major differences/enhancements between Selenium RC and Web driver?
  21. How to navigate to parent tag from a child tag in xpath?
  22. How to navigate to sibling node in xpath?
  23. What are major problems you encountered during automation? and you resolved?
  24. How to connect to excel sheet for test data reading?
  25. Which locator strategy is faster? Xpath or CSS why?
  26. What are different locator strategies exists?
  27. Which reported tool or component you used?
  28. How logging handled in your automation framework?
  29. What are user extension in selenium rc?
  30. How you update selenium server jar if needed?
  31. Is it possible to capture screen shot when system is turned to stand by mode?
  32. How test case dependency handled in your framework?
  33. Can selenium used to measure performance of web application?
  34. Explain getEval and runscript functions.
  35. How you handle auto complete search in selenium rc automation?

Handling alert, prompt and confirmation box using Selenium RC

This article explain about how to deal with java script alert, prompt and confirmation box.
Copy below html code and save it as test.html.

<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
function show_confirm()
{
var r=confirm("Press a button");
}
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
  {
  document.write("Hello " + name + "! How are you today?");
  }
}
</script>
</head>
</head>
<body>
<form action="">
<input type="button" onclick="show_alert()" value="Show alert box" id="alert"/>
<input type="button" onclick="show_prompt()" value="Show prompt box" id="prompt"/>
<input type="button" onclick="show_confirm()" value="Show confirm box" id="confirm"/>
<br/>
First name: <input type="text" name="firstname" id="firstname"/><br />
Last name: <input type="text" name="lastname" id="lastname"/>
</body>
</form>
</html>

Below selenium code handles these popups.

Alert Box:

Global.selenium.chooseOkOnNextConfirmation();
Global.selenium.click("alert");
System.out.println("Clicked on OK button in alert box");
String alert=Global.selenium.getAlert();//This is needed as If an confirmation is generated but you do not consume it with getConfirmation, the next Selenium action will fail.
Global.selenium.type("lastname""venkat");
Thread.sleep(10000); //just for to see actions by selenium. Not needed 

Same way you can handle both prompt and confirmation boxes.

Confirmation: 
Global.selenium.chooseOkOnNextConfirmation();
Global.selenium.click("confirm");
System.out.println("Clicked on OK button in confirm box");
String confirmation=Global.selenium.getConfirmation
Global.selenium.type("firstname""fname");
Thread.sleep(10000);//just for to see actions by selenium. Not needed

Prompt:
Global.selenium.chooseOkOnNextConfirmation();
Global.selenium.click("prompt");
System.out.println("Clicked on OK button in confirm box");
String prompt=Global.selenium.getPrompt();
Global.selenium.type("firstname""hiiii");
Thread.sleep(10000);

Tow points to remember are :
  1. Note that your first statement should be chooseOkOnNextConfirmation(), before clicking on an element which generates alert or popup
  2. GetAlert(), GetConfirmation() and GetPrompt(); commands should be issued after alert or popup has been generated, else subsequent statements will be failed.

Key press events using selenium RC

To handle key press events like to press page down, tab key or other keys selenium RC supports this by passing ASCII code of keys to keyDownNative function.

Syntax:

keyDownNative(String keycode);

Example:
  • For page down/scroll: keyDownNative("32"); //32 is ASCII code for space bar.
  • To press tab key: keyDownNative("9"); // 9 is ASCII code for Tab. 

Handling File upload using selenium.

Here I would like to share my experience on handling file upload using selenium.

To handle file upload using selenium RC (1.0 or higher) comes with two challenges.

1. Clicking on Browse/Upload button.
2. Selecting a file from windows dialog.

I will share handling this on both Fire fox and IE.

Fire Fox:

Its very simple when comes to handle file upload in Fire Fox. You just need to use selenium.type command for input file=type control.

Lets take below sample html code.

<input type="file" name="fileupload" id="filename" ></input>

All you just need to do is use below command to upload file.

selenium.type("//input[@name='fileupload']","c:\test.txt");

IE:

When it comes to IE its little tricky. Follow below steps.

1. Download AutoIt latest version.
2. Open new editor and past below code in editor.

If $CmdLine[0]<2 Then
Exit
EndIf

handleUpload($CmdLine[1],$CmdLine[2])

;define function to handleupload

Func handleUpload($title, $uploadFile)


if WinWait($title,"",4) Then
WinActivate($title)
ControlSetText($title,"","Edit1",$uploadFile) ;put file path into text fild
ControlClick($title,"","Button2")
Else
Return False
EndIf

EndFunc

4. Go to Tools menu build the code. It will generate an .exe (e.g. upload.exe)
5. Write a function in java as given below.

public void handleUpload(String windowtitle, String filepath) {
         String execute_file = "upload.exe";
         String cmd = "\"" + execute_file + "\"" + " " + "\"" + windowtitle + "\""
                                   + " " + "\"" + filepath + "\""; //with arguments
         try {
                 Process p = Runtime.getRuntime().exec(cmd);
                
         } catch (Exception e) {
                 e.printStackTrace();
         }
}

6. In your TC, remember that first you need to call above java function before click on browse button. Else control never comes back to your code if you click browse button first.

7. Now click on upload button using selenium.click("//input[@name='fileupload']").

Thats it!!

Finding broken images in a webpage using Selenium

We were checking for broken URLs using Selenium in the previous post. Now we are going to see how to find broken images in a webpage. Broken images are also called Red-X images. We have some tools in the market for finding red-x images on a website or webpage. For example, InSite which is a windows based application.

The same functionality can be possible with Selenium script. How do we do that?

  • We need to find the number of images on the page
  • We need to track the properties of each and every image.
  • Finally we need to extract the image size amd check if its broken or not
How to find the number of images on the page?

We can find the number using selenium.getXpathCount("//img").intValue() method.


selenium=new DefaultSelenium("localhost", 4444, "*firefox", "http://www.yahoo.com");
selenium.start();
selenium.open("/");
int linkCount = selenium.getXpathCount("//img").intValue();

How to track the properties for each and every image?

We can use the for loop and track the properties of the image one by one.


  for (int i = 1; i < imageCount; i++)
 {


String currentImage = "this.browserbot.getUserWindow().document.images[" + i + "]";
 
}

How to extract the image size from the image property?


String s = selenium.getEval("(!" + currentImage + ".complete) ? false : !(typeof " + currentImage + ".naturalWidth != \"undefined\" && " + currentImage + ".naturalWidth == 0);");
if(s.equals("false"))
{
System.out.println(selenium.getEval(currentImage + ".src"));
}

Find the complete script below:


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestBase;

public class FindBrokenImages extends SeleneseTestBase{

DefaultSelenium selenium;
public int invaildImg;

@BeforeMethod
public void SetUp()
{
        selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.yahoo.com/");
        selenium.start();
    }

@Test
public void testMethod() throws IOException {

invaildImg=0;
try
{
selenium.open("/");
}
catch (Exception e)
{
selenium.waitForPageToLoad("30000");
}
int imageCount = selenium.getXpathCount("//img").intValue();
FileOutputStream fout = new FileOutputStream ("broken_images.txt", true);
new PrintStream(fout).println("URL : " + selenium.getLocation());
new PrintStream(fout).println("--------------------------------------------");
    for (int i = 1; i < imageCount; i++) {
        String currentImage = "this.browserbot.getUserWindow().document.images[" + i + "]";
        String s = selenium.getEval("(!" + currentImage + ".complete) ? false : !(typeof " + currentImage + ".naturalWidth != \"undefined\" && " + currentImage + ".naturalWidth == 0);");
        if(s.equals("false")){
        // System.out.println(selenium.getEval(currentImage + ".src"));
         new PrintStream(fout).println(selenium.getEval(currentImage + ".src"));
         invaildImg++; }
    }
    new PrintStream(fout).println("Total broken images = " + invaildImg);
    new PrintStream(fout).println(" ");
    fout.close();
 


@AfterMethod
public void tearDown()
{
selenium.close();
selenium.stop();
}
}


The above script will identify all the broken images(if any) in yahoo.com and store the image URLs in a notepad file called broken_images.txt. If you want to check the broken images for N number of URLs, you can pass the parameters through Data Provider concept or Excel sheet using JXL package.

Finding the broken links in a webpage using Selenium


We heard about some Firefox plug-ins to find broken links in a webpage, like Link Checker, Xenu and etc. We need to install these plug-ins with Firefox browser and find the broken URLs or 404 pages.

We can write the Selenium script for the same functionality. How can we do that?
  • We need to find the number of links available on the page
  • We need to track each and every link
  • Finally we can get the response code for each and every URL or link with the help of HttpURLConnection Class and getResponseCode method.
How to find the number of links on the page?

We can find the number using selenium.getXpathCount("//a").intValue() method.

selenium=new DefaultSelenium("localhost", 4444, "*firefox", "http://www.yahoo.com");
selenium.start();
selenium.open("/");
int linkCount = selenium.getXpathCount("//a").intValue();

How to track each and every link on the page?

We can use the for loop and track the links one by one using this.browserbot.getUserWindow().document.links[] method. This will return the complete properties of the <a> tag of each URL. Then we can use selenium.getEval() method to extract only the HREF part of the <a> tag.

for (int i = 0; i < linkCount; i++) 
    {
     
        currentLink = "this.browserbot.getUserWindow().document.links[" + i + "]";
        temp = selenium.getEval(currentLink + ".href");

             }

How to find out the response code of the URL?

We can use HttpURLConnection Class and getResponseCode method for finding the reponse code of the URL.

public static int getResponseCode(String urlString) throws MalformedURLException, IOException {
    URL u = new URL(urlString); 
    HttpURLConnection huc =  (HttpURLConnection)  u.openConnection(); 
    huc.setRequestMethod("GET"); 
    huc.connect(); 
    return huc.getResponseCode();
}

Find out the complete Selenium Script below:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestBase;

public class BrokenURL extends SeleneseTestBase {
public int invalidLink;
String currentLink;
String temp;
public DefaultSelenium selenium;
@BeforeMethod
public void setUp() throws Exception
{
selenium=new DefaultSelenium("localhost", 4444, "*firefox", "http://www.yahoo.com");
selenium.start();
}
@Test
public void testUntitled() throws Exception {
FileOutputStream fout = new FileOutputStream ("broken_links.txt", true);
invalidLink=0;
selenium.open("/");
int linkCount = selenium.getXpathCount("//a").intValue();
    
new PrintStream(fout).println("URL : " + selenium.getLocation());
new PrintStream(fout).println("--------------------------------------------");
    for (int i = 0; i < linkCount; i++) 
    {
     int statusCode=0;
    
        currentLink = "this.browserbot.getUserWindow().document.links[" + i + "]";
        temp = selenium.getEval(currentLink + ".href");
        statusCode=getResponseCode(temp);
        if (statusCode==404)
        {
         new PrintStream(fout).println(selenium.getEval(currentLink + ".href") + " "+ statusCode);
         invalidLink++; 
        }
    }
    new PrintStream(fout).println("Total broken Links = " + invalidLink);
    new PrintStream(fout).println(" ");
fout.close();
    System.out.println(currentLink);
    System.out.println(temp);
}
public static int getResponseCode(String urlString) throws MalformedURLException, IOException {
    URL u = new URL(urlString); 
    HttpURLConnection huc =  (HttpURLConnection)  u.openConnection(); 
    huc.setRequestMethod("GET"); 
    huc.connect(); 
    return huc.getResponseCode();
}


public void tearDown()
{
selenium.close();
selenium.stop();
}
    
}

The above script will identify all the broken links(if any) in yahoo.com and store the 404 URLs in a notepad file called broken_links.txt. If you want to check the broken links for N number of URLs, you can pass the parameters through Data Provider concept or Excel sheet using JXL package.


Handling Authentication dialog box using Selenium and AutoIT

As we know Selenium is an automation tool for web based applications and it handles only web elements and popups which triggered from web pages. Sometimes we get Window based popups like Authentication dialog box, Security warnings while using the web pages. The question would be how to handle these popups from Selenium?

The answer would be there is no straight forward method or command in selenium to handle these popups. We can use getAlert() and ChooseOKOnNextConfirmation() methods only when the popups are triggered from web pages.

In this scenario, we need to go for AutoIT scripts which can handle these kind of popups. These scripts can be integrated with Selenium code. Follow these steps to handle Authentication dialog box using Selenium and AutoIT.

1. Download AutoIT tool. It can be downloaded from http://www.autoitscript.com/site/autoit/downloads/

Note: Please download AutoIT Full Installation

2. While installing AutoIT, you will get two options: Run the Script and Edit the Script. If you are going to use the script without any modification, choose Run the Script option. If you want to customize the scripts, choose Edit the Script option (Recommended as we always needs to customize the scripts for our needs. Sometimes we need to create our own scripts.)

3. Once installed you can find all the sample scripts in the Example folder. Assume we have a sample script for handling the Authentication box which is Login.au3 (extension of the AutoIT scripts will be .au3). Right click on that file and choose Edit option. Find the script below:


WinWaitActive("Authentication Required","","20")
 If WinExists("Authentication Required") Then
 Send("userid{TAB}")
 Send("password{Enter}")
 EndIf


4.Customize the scripts according to your need. 

For example, You can type your username and password in the script.


WinWaitActive("Authentication Required","","20")
 If WinExists("Authentication Required") Then
 Send("selenium_user{TAB}")
 Send("selenium123{Enter}")
 EndIf

5. Save the file once you modify all the required changes.

6. Now, open the application Aut2Exe which will convert your AutoIT script into EXE format.



7. Now, call this EXE file from your selenium code as below.

@Test
public void testUntitled()
{
         Runtime run = Runtime.getRuntime();
         Process pp=run.exec("C:\\Program Files\\AutoIt3\\Examples\\Login.exe");
         selenium.open(URL);
         ...................
         ...................
}

8. Execute you selenium code and check if the AutoIT script handles the Authentication Required dialog box.

Even we can handle File Save As, Open With dialog boxes using AutoIT and Selenium. It will be covered in my coming blogs. Stay connected :-)

Browser window not getting maximized while using Selenium windowMaximize() method

Unlike QTP, selenium tests can be executed without maximizing the browser window. Unless you click on the browser window, it will not get maximized. So that we can work on other things when the tests gets executed. Though its useful for us, sometimes we want to see whats going on in the web application and we maximize the browser window from taskbar.

Even we have Selenium windowMaximize() method to maximize the web application. But, if you see, it does maximize!!!, actually it does, but the application (broswer window) will not get the focus. When selenium.windowMaximize() gets executed, the application gets maximized and still it stays in the task bar. Manually we need to click on the browser tab on the taskbar to get the focus of that application.

Normally we use the below code for starting Selenium and maximizing the browser window.

@Before
public void setUp()
{
         selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.co.in/");
         selenium.start();
         selenium.windowMaximize();
         selenium.windowFocus();
}
@Test
public void testUntitled()
{
         selenium.open("/");
         .............................
         .............................
}

But, most of the times your browser window doesn't get maximized. Some time it gets maximized only if you dont have any other window opened in your taskbar. We have a workaround to resolve this issue. Thats Java Robot class.

We can use Java Robot class to minimize all the windows before opening the URL using Selenium object. We need to activate Window and M keys using robot class. This will minimize all the applications opened. Then we can call selenium.windowMaximize() method which will maximize your browser window. Use the below code.

@Before
public void setUp()
{

         selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.co.in/");
         selenium.start();
         Robot robot = new Robot();
         robot.keyPress(KeyEvent.VK_WINDOWS);
         robot.keyPress(KeyEvent.VK_M);
         robot.keyRelease(KeyEvent.VK_WINDOWS);
         robot.keyRelease(KeyEvent.VK_M);
         Thread.sleep(1000);
         selenium.windowMaximize();
         selenium.windowFocus();
         selenium.windowMaximize();

         selenium.windowFocus();
}

@Test
public void testUntitled()
{
         selenium.open("/");
         .............................
         .............................
}

Hope this code helps to maximize your browser window when you execute your Selenium tests.

WebDriver with JUNIT


import java.util.concurrent.TimeUnit;
import junit.framework.Assert;
import  org.junit.Assert.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;


public class WebDriverJunit {

public static WebDriver oBrowser;
@BeforeClass
public static void Selenium_init()
{
oBrowser=new FirefoxDriver();
oBrowser.manage().window().maximize();
oBrowser.manage().timeouts().pageLoadTimeout(15, TimeUnit.SECONDS);
oBrowser.get("http://www.bing.com");
}

@AfterClass
public static void Selenium_End()
{
oBrowser.quit();
}
@Test
public void Validate_Edit()
{
WebElement oEdit;
try
{
oEdit=oBrowser.findElement(By.id("sb_form_q"));
Assert.assertEquals("", oEdit.getText());
}
catch(Exception e)
{
Assert.fail(e.getMessage());
}
}

@Test
public void Search()
{
WebElement oEdit,oButton;
String sPageSource;
try
{
oEdit=oBrowser.findElement(By.id("sb_form_q"));
oButton=oBrowser.findElement(By.id("sb_form_go"));
oEdit.sendKeys("Selenium");
oButton.click();
sPageSource=oBrowser.getPageSource();
oBrowser.navigate().back();
if (sPageSource.lastIndexOf("Selenium")<100)
{
Assert.fail("No Proper result");
}
}
catch(Exception e)
{
Assert.fail(e.getMessage());
}
}
}

Simple Webdriver program to open Browser,print browser info and close Browser

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class WebDriverDemo {

    public static WebDriver oBrowser;
    public static String sUrl="http://www.bing.com";
     
    public static void main(String[] args)
    {  
        boolean bIsBrowserOpened;
      
        bIsBrowserOpened=OpenBrowser();
        if(bIsBrowserOpened)
        {
            Get_BrowserInfo();
            CloseBrowser();
        }
      }
    public static boolean OpenBrowser()
    {
        try
        {
            oBrowser=new FirefoxDriver();
            oBrowser.get(sUrl);
            try
            {
                Thread.sleep(5000L);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return true;
        }
        catch(Exception e)
        {
            System.err.println(e.getMessage());
            return false;
        }
    }
   public static void Get_BrowserInfo()
    {
        String sTitle,sSource;
        sTitle=oBrowser.getTitle();
        sSource=oBrowser.getPageSource();
        System.out.println("Page Title =" + sTitle);
        System.out.println("****************************************");
        System.out.println("Page Source.......");
        System.out.println(sSource);
    }
  
    public static void CloseBrowser()
    {
        oBrowser.close();
    }
  
}

Detecting no.of popups , Fetching their titles and closing popups using webdriver

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.*;

// ---- Detecting no.of popups and fetching
//      their titles and closing popups
// ---- closing all parent and child window with .quit() method.

public class WebDriverPopupDemo {

    /**
     * @param args
     */
    public static WebDriver oBrowser;
    public static String sUrl = "http://naukri.com";
// --- Reading existing text from TextBox
    public static void main(String[] args)
    {
        boolean bIsBrowserOpened;
      
        bIsBrowserOpened = OpenBrowser();
      
        if (bIsBrowserOpened)
        {
          
            Get_Popup_Count();
            Get_Popup_Title();
            Closing_Popups();
            CloseBrowser();  
        }
      
  
    }
  
    public static boolean OpenBrowser()
    {
        try
        {
            oBrowser = new FirefoxDriver();
            oBrowser.get(sUrl);
            try
                {
                    Thread.sleep(5000L);
                }
            catch (Exception e)
                {
                    e.printStackTrace();
                }
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
            return false;
        }
        return true;
      
    }
  
    public static void Get_BrowserInfo()
    {
        String sTitle, sSource;
        sTitle = oBrowser.getTitle();
        sSource = oBrowser.getPageSource();
        System.out.println("Page Title ="+sTitle);
        System.out.println("******");
        System.out.println("Page Source....");
        System.out.println(sSource);
    }
  
    public static void CloseBrowser()
    {
        // oBrowser.close(); // --- closes only parent
      
        oBrowser.quit(); // --- closes all, including popups..
    }
  
    public static void Get_Popup_Count()
    {
        int iPopupCount;
      
        iPopupCount = oBrowser.getWindowHandles().size();
      
        if (iPopupCount == 1)
        {
            System.out.println("Only! parent window & no popups");
          
        }
        else
        {
        System.out.println("parent and popup both exist");  
        System.out.println("Total No of Windows = "+iPopupCount);
      
        }
    }
  
    public static void Get_Popup_Title()
    {
        int iPopupCount, iPopup;
        Object[] lsAllHandles;
        String sWindowTitle;
      
        lsAllHandles = oBrowser.getWindowHandles().toArray();
      
        iPopupCount = lsAllHandles.length;
      
        for (iPopup=0; iPopup<iPopupCount; iPopup++)
        {
            sWindowTitle = oBrowser.switchTo().window((String) lsAllHandles[iPopup]).getTitle().toString();
          
            if (iPopup==0)
            {
            System.out.printf("\n Main window title = %s",
                    sWindowTitle);
            }
            else
                System.out.printf("\n window (%d of %d) = %s",
                        iPopup, iPopupCount-1,sWindowTitle);
        }
      
      
    }
  
    public static void Closing_Popups()
    {
        int iPopupCount, iPopup;
        Object[] lsAllHandles;
        String sWindowTitle;
      
        lsAllHandles = oBrowser.getWindowHandles().toArray();
      
        iPopupCount = lsAllHandles.length;
      
        if (iPopupCount>0) // -- there are popups
        {
      
            for (iPopup=1; iPopup<iPopupCount; iPopup++)
            {
                sWindowTitle = oBrowser.switchTo().window((String) lsAllHandles[iPopup]).getTitle().toString();
              
                System.out.printf("\n Closing Pop Window (%d of %d)=%s",
                        iPopup,iPopupCount-1,sWindowTitle);
                oBrowser.switchTo().window((String)lsAllHandles[iPopup]).close();
            }
            oBrowser=oBrowser.switchTo().window((String)lsAllHandles[0]);
        }
      
      
    }
  
  

}

Angular JS Protractor Installation process - Tutorial Part 1

                     Protractor, formally known as E2E testing framework, is an open source functional automation framework designed spe...