Pages

Search This Blog

Friday, December 3, 2010

How to automate onblur through selenium RC .

How to automate onblur through selenium RC .
How to automate lost focus through selenium.


I faced the problem while automating the form submit. All of the form fields are having some action on their lost focus.
The onblur event occurs when an object loses focus.
For example : I have two fields First Name and Last Name. When i enter first name and press tab then it loses its focus and onblur function gets called.
and its calls upperCase and it changes the first name in Upper case.
the same case with Last Name. When i enter last name and press tab it calls blur function lowerCase and changes the letters in lower case.

But the problem in automation is i cant automate lost focus. when we type in first name and last name it simply types in first name and last name text box.
It does not call onblur function upper case and lower case and does not change the letter respectively.

so, fireEvent is a special command in selenium which helps in automating onblur function.

this is html of the element and blur javascript functions


<html>
<head>
<script type="text/javascript">
function upperCase()
{
var x=document.getElementById("fname").value;
document.getElementById("fname").value=x.toUpperCase();
}
function lowerCase()
{
var x=document.getElementById("lname").value;
document.getElementById("lname").value=x.toLowerCase();
}
</script>
</head>
<body>
Enter your First Name: <input type="text" id="fname" onblur="upperCase()" />
<br />
Enter your Last Nast: <input type="text" id="lname" onblur="lowerCase()" />
</body>
</html>


when we write simple selenium RC code

 selenium.type("fname", "niraj");
 selenium.type("lname", "KUMAR");
 
it doest call blur functions to change cases of the first name and last name.

But by using fireEvent fuction of selenium we can call blur function.

 selenium.type("fname", "niraj");
 selenium.fireEvent("fname", "blur");
 selenium.type("lname", "KUMAR");
 selenium.fireEvent("lname", "blur");

How this works is :

First this will type "niraj" in First Name and then selenium.fireEvent("fname", "blur"); this will call the onblur fuction "upperCase()" which changes the First Name in upper case "NIRAJ".
then it types in Last Name and then selenium.fireEvent("lname", "blur"); which means it will press tab and lost the function and on the lost focus it calls
blur function lowerCase which changes the Last Name in lower case.

Thursday, October 21, 2010

How to verify the text ignoring cases sensitivity in selenium ?

How to verify the text ignoring cases sensitivity in selenium ?

Some times we need to verify the text on the webpage no matter is upper cases or lower cases or proper.
We just need to verify the text on the web page ignoring their cases sensitivity.
REGEXPI is used to avoid cases sensitive to verify the text on the page.

Lets say i want to verify the text "Automationtricks is good blog for selenium" No matter its in upper cases or lower case or proper case.

Then use REGEXPI in selenium command selenium.isTextPresent or verifyTextPresent.


<tr>
    <td>verifyTextPresent</td>
    <td>regexpi:AUTOMATIONTRICKS IS GOOD BLOG FOR SELENIUM</td>
    <td></td>
</tr>

<tr>
    <td>verifyTextPresent</td>
    <td>regexpi:AUTOMATIONTRICKS is good blog for selenium</td>
    <td></td>
</tr>

<tr>
    <td>verifyTextPresent</td>
    <td>regexpi:AUTOMAtionTRICKS Is GoOd Blog for SELENIUM</td>
    <td></td>
</tr>

<tr>
    <td>verifyTextPresent</td>
    <td>regexpi:automationtricks is good blog for selenium</td>
    <td></td>
</tr>


In Selenium RC

verifyTrue(selenium.isTextPresent("regexpi:AUTOMATIONTRICKS IS GOOD BLOG FOR SELENIUM"));

verifyTrue(selenium.isTextPresent("regexpi:AUTOMATIONTRICKS is good blog for selenium"));

verifyTrue(selenium.isTextPresent("regexpi:AUTOMAtionTRICKS Is GoOd Blog for SELENIUM"));

verifyTrue(selenium.isTextPresent("regexpi:automationtricks is good blog for selenium"));


Wednesday, October 6, 2010

How to verify value in drop down list.

How to verify value in drop down list.
We somehow manage to find the element on the page but its difficult to fund element with some specific attributes.
Take an example How to find some value is in drop down list or now? To find element drop down is easy but to find a drop down having some specific
value in their list is difficult.

Go to www.ebay.in you will see there is drop down along with search text box.
How to veify a specific value "Collectibles" is in drop down list.

Using Xpath:

<tr>
 <td>verifyElementPresent</td>
 <td>//select[@id='_sacat']/option[contains(text(),'Collectibles')]</td>
 <td></td>
</tr>

verifyTrue(selenium.isElementPresent("//select[@id='_sacat']/option[contains(text(),'Collectibles')]"));


Using CSS:

<tr>
 <td>verifyElementPresent</td>
 <td>css=select#_sacat>option:contains("Fun")</td>
 <td></td>
</tr>

verifyTrue(selenium.isElementPresent("css=select#_sacat>option:contains(\"Fun\")"));

<tr>
 <td>verifyElementPresent</td>
 <td>css=select>option:contains("Fun")</td>
 <td></td>
</tr>


How to select the value in drop down using regular expression.

There are situation when we need to select the drop down value with some partial text .
With the help of regular expression we can select the drop down value

<tr>
 <td>select</td>
 <td>_sacat</td>
 <td>label=regexp:Fun*</td>
</tr>

selenium.select("_sacat", "label=regexp:Fun*");


Friday, October 1, 2010

How to use CSS in Selenium to locate an element

XPath locator is one of the most precise locator. But this has a disadvantage of its locator types thats is its slowness.
This disadvantage of xpath you can see when running the tests under IE while Firefox works with xpath pretty faster than IE.
The main thing is that tests which intensively use XPath work extremely slow under IE and this feature is the cause of huge variety of problems related to execution speed as well as quality of the tests itself especially during operations with dynamic content.
For this reason CSS locators can be good alternative of XPath. What can we do with CSS locators?

CSS locator will give you clear picture of your element hierarchy
lets say your xpath of an element is like,

xpath=//div//span/a

the same locatore can be identified by CSS is .

css=div * span > a

from the above example there are two symbol are being used to locate an element.

1) "/" in xpath is just a next level of DOM element hierarchy and same used in CSS is ">"
2) "//" in xpath is any DOM object hierarchy level under current object and same used in CSS is "*"

The way we use attributes in xpath we can use attributes in css as well. lets say your element's xpath is like this

//input[@name='continue' and @type='button']

can be written in CSS

css=input[name='continue'][type='button']
or
css=input[name=continue][type=button]

in xpath we can check the partial attribute value matching but in CSS we can't.

lets say your element is like this

<div title="here is m multiword title" />

so the xpath to locate this element is .

xpath=//div[contains(@title,"title")]

and same can be used in CSS like

css=div[title~=title]

But if your element is like this

<div title="my_title" />

then CSS locator css=div[title~=title] wont work here .

CSS provides us the easy way to specify the element.
lets say your element is like this,

<input id="username"></input>

we can write in xpath like this

xpath=//input[@id="username"]

and same can be specified in CSS

css=input#username

so whenever we want to identify any element with their id then we use #

lets say your element is like this,

<input class="password"></input>

then xpath is

xpath=//input[@class="password"]

and corresponding CSS is

css=input.password

so whenever we want to identify any element with their class then we use .

below are the element sturcture used in above examples.

<html>
<body>
<form>
 <input id="username"></input>
 <input class="password"></input>
 <input name="continue" type="button"></input>
 <input name="cancel" type="button"></input>
 <input value="a86b504a-faff-4a18-92d8-68720331c798" name="vid" type="hidden"><input value="LF_c10cf6d6" name="lf_cid" type="hidden"></form>
 </body>
</html>



An interesting feature of CSS in Selenium :Sub-String matches.

^= Match a prefix
$= Match a suffix
*= Match a substring

1 css=a[id^='id_prefix_']

A link with an “id” that starts with the text “id_prefix_”

2 css=a[id$='_id_sufix']

A link with an “id” that ends with the text “_id_sufix”

3 css=a[id*='id_pattern']

A link with an “id” that contains the text “id_pattern”

Without specifying the type of element we can identify the element
to identify the google search button we can use Css like this

css=center > #sbds > #sblsbb > input

these CSS features are awesome more details can be found on
How to use CSS in Selenium extensively
and if you want to know in depth then visit this page.
http://www.w3.org/TR/css3-selectors/

Tuesday, September 28, 2010

How to locate an element which have same name and same atrributes in selenium

Automation using selenium is a great experience. It provides many way to identif an object or element on the web page.
But sometime we face the problems of idenfying the objects on a page which have same attributes. When we get more than
one element which are same in attribute and name like multiple checkboxes with same name and same id. More than one button having
same name and ids. There are no way to distingues those element. In this case we have problem to instruct selenium to identify a perticular
object on a web page.
I am giving you a simple example . In the below html source there are 6 checkboxes are there having same type and same name.
It is really tough to select third or fifth.

<html>
<body>
<input type='checkbox' name='chk'>first
<br><input type='checkbox' name='chk'>second
<br><input type='checkbox' name='chk'>third
<br><input type='checkbox' name='chk'>forth
<br><input type='checkbox' name='chk'>fifth
<br><input type='checkbox' name='chk'>sixth
</body>
</html>


Thare are some function we can use in Xpath to identify the abject in above cases.
An XPath expression can return one of four basic XPath data types:

* String
* Number
* Boolean
* Node-set

XPath Type : Functions
Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()
String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-space(), translate()
Boolean : boolean(), not(), true(), false(), lang()
Number : number(), sum(), floor(), ceiling(), round()

I will show you how we can use some of these above functions in xpath to identify the objects.

Node Set : last()


In the above html file there are six checkboxes and all are having same attributes (same type and name)
How we can select the last checkbox based on the position. We can use last() function to indentify the last object among all similar objects.
Below code will check or uncheck the last checkbox.

selenium.click("xpath=(//input[@type='checkbox'])[last()]");

How we can select the second last checkbox and third last checkbox. We can use last()- function to indentify the last object among all similar objects.
Below code will check or uncheck the second last checkbox and thrid last checkbox respectively.

selenium.click("xpath=(//input[@type='submit'])[last()-1]");
selenium.click("xpath=(//input[@type='submit'])[last()-2]");


Node Set : position()

If you want to select any object based on their position using xpath then you can use position() function in xpath.
You want to select second checkbox and forth checkbox then use below command

selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");
selenium.click("xpath=(//input[@type='checkbox'])[position()=4]");

above code will select second and forth checkbox respectively.

String : starts-with()

Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically.
Each time id gets generated differently. So to handle this situation we use some JavaScript functions.

XPath: //button[starts-with(@id, 'continue-')]  


Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element can be located based on the ‘suggest’ class without having
to couple it with the ‘top’ and ‘business’ classes using the following

XPath: //input[contains(@class, 'suggest')].



Example: How to click on link on the page which has many links with same name and attributes.
Below is the example of your html which has 3 links with same name and same attributes


<html>
<body>
<a href="http://www.google.com" name="a1">Link</a>
<a href="http://www.yahoo.com" name="a1">Link</a>
<a href="http://www.gmail.com" name="a1">Link</a>
</body>
</html>



If you want to click on first link then use below command

<tr>
 <td>clickAndWait</td>
 <td>xpath=(//a[@name='a1'])[position()=1]</td>
 <td></td>
</tr>

If you want to click on second link then use below command

<tr>
 <td>clickAndWait</td>
 <td>xpath=(//a[@name='a1'])[position()=2]</td>
 <td></td>
</tr>

If you want to click on last link or third link then use below command

<tr>
 <td>clickAndWait</td>
 <td>xpath=(//a[@name='a1'])[last()]</td>
 <td></td>
</tr>

OR

<tr>
 <td>clickAndWait</td>
 <td>xpath=(//a[@name='a1'])[position()=3]</td>
 <td></td>
</tr>

Selenium RC.

Click on first link
selenium.click("xpath=(//a[@name='a1'])[position()=1]");
selenium.waitForPageToLoad("80000");
Click on second link
selenium.click("xpath=(//a[@name='a1'])[position()=2]");
selenium.waitForPageToLoad("80000");
Click on last link
selenium.click("xpath=(//a[@name='a1'])[last()]");
selenium.waitForPageToLoad("80000");
Click on thrid link
selenium.click("xpath=(//a[@name='a1'])[position()=3]");
selenium.waitForPageToLoad("80000");

For rest of the function please keep reading my blogs i will be posting very soon.


Monday, September 27, 2010

How to write in Iframe in selenium

Selenium is unable to type in iframe. But we can write in it by identifying the iframe using css.
When you write any mail in gmail you can see the body is a iframe we can write in it using below commands
Selenium IDE



<tr>
 <td>storeEval</td>
 <td>var bodytext=" Writing text in iframe body with the help of http://automationtricks.blogspot.com ";  var iframe_locator="css=table:contains('Subject:') +*  iframe";   var iframe_body=selenium.browserbot.findElement(iframe_locator).contentWindow.document.body;   if (browserVersion.isChrome){    iframe_body.textContent=bodytext; }  else if(browserVersion.isIE){ iframe_body.innerText=bodytext; }</td>
 <td></td>
</tr>


Selenium RC.


String  = selenium.getEval("var bodytext=\" Writing text in iframe body with the help of http://automationtricks.blogspot.com \";  var iframe_locator=\"css=table:contains('Subject:') +*  iframe\";   var iframe_body=selenium.browserbot.findElement(iframe_locator).contentWindow.document.body;   if (browserVersion.isChrome){    iframe_body.textContent=bodytext; }  else if(browserVersion.isIE){ iframe_body.innerText=bodytext; }");

How to locate an element based on their label in selenium

How to locate an element based on their label.
Some time it difficult to locate an element usiing DOM, HTML and xpath. In that case we use to locate the element with the
help of their lables.

For example : Go to yahoo login page

selenium.open("https://login.yahoo.com");

Based on the lable "Yahoo ! ID" we will read the text box and type in.

selenium.type("css=label:contains(\"Yahoo! ID\")+input", "niraj");

Based on the lable "Password" we will locate the text box for passowrd and type in.

selenium.type("css=label:contains(\"Password\")+input", "pass");

Go to yahoo registrantion page.


selenium.open("https://edit.yahoo.com/registration?.intl=us");

Based on Name label we will type in First Name text box. 

selenium.type("css=label:contains(\"Name\")+div>input", "niraj");

Based on Name label we will  type in Last name text box.

selenium.type("css=label:contains(\"Name\")+div>input+input", "kumar");

Based on Gender lable we will select the gender from drop down.

selenium.select("css=label:contains(\"Gender\")+div>select", "label=Male");

Based on Birthday lable we will select the month from drop down.

selenium.select("css=label:contains(\"Birthday\")+div>select", "label=January");

Based on Birthday lable we will type the date in date text box.

selenium.type("css=label:contains(\"Birthday\")+div>select+input", "2");

Based on Birthday lable we will type the year in year text box.

selenium.type("css=label:contains(\"Birthday\")+div>select+input+input", "1982");

Based on country lable we will select India in country drop down box.

selenium.select("css=div>label:contains(\"Country\")+div>select", 
"label=India");


+ Is used to point the element on the same node in tree of css.
<label class="label" for="name">Name</label>
<div class="collection" id="name">
<input type="text" title="First Name" name="firstname" id="firstname" value="" size="32" maxlength="32" class="" autocomplete="off">
<input type="text" title="Last Name" name="secondname" id="secondname" value="" size="32" maxlength="32" class="" autocomplete="off">
</div>
to access firstname text box
selenium.type("css=label:contains(\"Name\")+div>input", "niraj");
to access secondname its the same label of div but on the second place
selenium.type("css=label:contains(\"Name\")+div>input+input", "kumar");


> Is used to point the element one node down in the tree of css.
to access firstname text box
selenium.type("css=label:contains(\"Name\")+div>input", "niraj");

Sunday, September 26, 2010

How to upload a file in selenium

How to upload a file in selenium with the help of AutoIT

Recently, I had the challenge of writing some automation for a workflow which included uploading a file because uloading a file works on windows component.
selenium is unable to access windows components and it will be handled through AutoIT.
Once you are able to click on browse button and a dialog box is open to choose the file then you just run a AutoIT script which will help to select the file from your local or remote drive and control will come to your web page to proceed with selenium.

Step to choose a file from your local or remote drive



Step 1.

Download the AutoIT and intall it.

Download AutoIT



setp 2.

write a AutoIT script to choose a file from your local or remote drive.



#include <IE.au3>
; Internet Explorer is partly integrated in shell.application
$oShell = ObjCreate("shell.application") ; Get the Windows Shell Object
$oShellWindows=$oShell.windows   ; Get the collection of open shell Windows
$MyIExplorer=""
for $Window in $oShellWindows    ; Count all existing shell windows
  ; Note: Internet Explorer appends a slash to the URL in it's window name
  if StringInStr($Window.LocationURL,"http://") then
      $MyIExplorer=$Window
      exitloop
  endif
next
$oForm = _IEGetObjByName ($MyIExplorer, "UploadedFile")
_IEAction($oForm, "click")
WinActivate("Choose file");
Local $file = "C:\Documents and Settings\intelizen\Desktop\selenium.txt"
ControlSetText("Choose file", "", "Edit1", $file )
ControlClick("Choose file", "", "Button2")





setp 3.

Complie AutoIT script and make exe of that script.

Right click on that saved script file and click on "Compile script" from context menu. This will make an exe file of that script.


setp 4.

Call that exe in selenium.

Process proc = Runtime.getRuntime().exec("C:\\niraj\\FileUpload.exe");

Download AutoIT script
Download exe file of AutoIT script


If you want to test this script then just download the script exe file and click on browse button on web page and run this exe file. Just make sure you have your file in correct path by changing this line of script in the second step
Local $file = "c:\yourpath\howtoupload.doc"
in above line of script change your file path then make exe of your script then click on browse button on your web page then run this exe . I am sure this would work.

If it still is nor working then change the script like


#include <IE.au3>
; Internet Explorer is partly integrated in shell.application
$oShell = ObjCreate("shell.application") ; Get the Windows Shell Object
$oShellWindows=$oShell.windows   ; Get the collection of open shell Windows
$MyIExplorer=""
for $Window in $oShellWindows    ; Count all existing shell windows
  ; Note: Internet Explorer appends a slash to the URL in it's window name
  if StringInStr($Window.LocationURL,"http://") then
      $MyIExplorer=$Window
      exitloop
  endif
next
$oForm = _IEGetObjByName ($MyIExplorer, "UploadedFile")
_IEAction($oForm, "click")

WinActivate("File Upload");
Local $file = "c:\yourpath\howtoupload.doc"
ControlSetText("File Upload", "", "Edit1", $file )
ControlClick("File Upload", "", "Button2")

In above script you might need to change your file path and browse button name and the title of you dialog box.

Download the AutoIT script


Example

Below is an example in selenium RC for uploading your file which works on


Step 1.

First download the zip file and extact the files . There are 2 files in this one "Browse.a3" is for clicking on browse button and other one is "upload.a3" for selecting the path from your location and open it in dialog box.Make exe of both files and use in selenium RC like in second step.

Download the zip file

Step 2.

Write a selenium rc script like below . This script will works file with internet explorer. This script will open http://www.pdfonline.com/convert-pdf there you
will get a browse button. when Process proc = Runtime.getRuntime().exec("C:\\Documents and Settings\\nirkumar\\Desktop\\Browse.exe"); executes then it will
identify the browser and try to identify the element "Browse button" In attached files "Browse.au3" identtifies the button with name of "File1" but
if you have differen name of your browse button then open then "Browse.au3" file and change the line " $oForm = _IEGetObjByName($MyIExplorer, "Your browse button name") and save it and
make exe of that file. Now call this file in selenium. It will click on browse button.


import java.io.IOException;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class Uploadingfiles extends SeleneseTestCase{
 Selenium selenium;
 public static final String MAX_WAIT_TIME_IN_MS="60000";
 private SeleniumServer seleniumServer;
  public void setUp() throws Exception {
     
     RemoteControlConfiguration rc = new RemoteControlConfiguration();
          rc.setSingleWindow(false);
          seleniumServer = new SeleniumServer(rc);
          selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.pdfonline.com/convert-pdf/");
          seleniumServer.start();
          selenium.start();
          }
   
public void testgoogling() throws IOException {
selenium.open("http://www.pdfonline.com/convert-pdf/");

Process proc = Runtime.getRuntime().exec("C:\\Documents and Settings\\nirkumar\\Desktop\\Browse.exe");
Process proc1 = Runtime.getRuntime().exec("C:\\Documents and Settings\\nirkumar\\Desktop\\Upload.exe");
pause(10000);
}
}



When browse button clicked it will open a choose file dialog box. then Process proc1 = Runtime.getRuntime().exec("C:\\Documents and Settings\\nirkumar\\Desktop\\Upload.exe"); line will be executed
and this will set the file path and click open. In the attached zip you will get one file "Upload.a3" in this file you have to set the path of your file which you want to upload
Local $file = "Your file location" this will set the path of your file and click on open button.


Note : This work with Internet explorer only.

How to upload a file in selenium with the help of AutoIT

How to upload a file in selenium with the help of AutoIT
Recently, I had the challenge of writing some automation for a work flow which included uploading a file because uploading a file works on windows component.
selenium is unable to access windows components and it will be handled through AutoIT.
Once you are able to click on browse button and a dialog box is open to choose the file then you just run a AutoIT script which will help to select the file from your local or remote drive and control will come to your web page to proceed with selenium.

Step to choose a file from your local or remote drive

Step 1.

Click on browse button on your web page and go to second step.If you are unable to click on browse button then visit below page.

How to click on browse button

setp 2.
write a AutoIT script to choose a file from your local or remote drive.

WinActivate("Choose file");
Local $file = "c:\yourpath\howtoupload.doc"
ControlSetText("Choose file", "", "Edit1", $file )
ControlClick("Choose file", "", "Button2")



setp 3.
Complie AutoIT script and make exe of that script.

Right click on that saved script file and click on "Compile script" from context menu. This will make an exe file of that script.

setp 4.
Call that exe in selenium.

Process proc = Runtime.getRuntime().exec("C:\\Documents and Settings\\nirkumar\\Desktop\\Browse.exe");


Download AutoIT script
Download exe file of AutoIT script

If you want to test this script then just download the script exe file and click on browse button on web page and run this exe file. Just make sure you have your file in correct path by changing this line of script in the second step
Local $file = "c:\yourpath\howtoupload.doc"
in above line of script change your file path then make exe of your script then click on browse button on your web page then run this exe . I am sure this would work.
If it still is nor working then change the script like

WinActivate("File Upload");
Local $file = "c:\yourpath\howtoupload.doc"
ControlSetText("File Upload", "", "Edit1", $file )
ControlClick("File Upload", "", "Button2")

How to click on browse button in selenium with the help of AutoIT

Recently, I had the challenge of writing some automation for a work flow which included uploading a file, and then downloading a file later in the work flow.
AutoIT
Autoit is a freeware windows testing tool. Autoit allows you accessing windows components similar to QTP. Basically once you have identified the id of the component on the screen you can use it by either clicking on it, typing in something. Using Autoit we can identify the internet explorer “Choose file” or Firefox

“File Upload” windows and enter the correct value to the input

field after which you will press the open button.

Step to click on browse button.
Step 1.
Download the AutoIT and intall it.

Download AutoIT

setp 2.
write a AutoIT script to click on browse button and save it.



#include <IE.au3>
; Internet Explorer is partly integrated in shell.application
$oShell = ObjCreate("shell.application") ; Get the Windows 

Shell Object
$oShellWindows=$oShell.windows   ; Get the 

collection of open shell Windows
$MyIExplorer=""
for $Window in $oShellWindows    ; Count all existing 

shell windows
  ; Note: Internet Explorer appends a slash to the URL in it's 

window name
  if StringInStr($Window.LocationURL,"http://") then
      $MyIExplorer=$Window
      exitloop
  endif
next
$oForm = _IEGetObjByName ($MyIExplorer, "UploadedFile")
_IEAction($oForm, "click")



setp 3.
Compile AutoIT script and make exe file of that script.

Right click on that saved script file and click on "Compile script" from context menu. This will make an exe file of that script.


setp 4.
Call that exe in selenium.


Process proc = Runtime.getRuntime().exec("C:\\Documents and Settings\\nirkumar\\Desktop\\Browse.exe");


This will click on browse button and open choose file or upload file dialog box.
Download AutoIT script
Download exe of that script

If you want to test this script works then download the exe and open the page which has browse button and run(double click on this exe) this exe file. i am sure this
will click on your browse button and open a dialog box. If it does not then definitely your browse button has some other name than "UploadedFile" then in the step 2 change the button name and make exe of that script and run it.

NOTE: This will work in Internet explorer.

Tuesday, September 14, 2010

How to share a variable in two test cases

How to share a variable in more than one test case.
We Create a variable in one test case and use in another test cases. If these test cases are running seperately and independetely then those variable
cannot shared. But if we run all test cases in test suite then one varaible declared in one testcase can be used in another
Follow these steps.
Create your test cases saparetly and call them in a test suite.
1.Create first test case
Test1.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Propagate_Negative_API_UK</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Propagate_Negative_API_UK</td></tr>
</thead><tbody>
<!------------------ Initialization steps ---------->
<tr>
 <td>store</td>
 <td>varaible from first test1</td>
 <td>vartest1</td>
</tr>


<tr>
 <td>open</td>
 <td>http://www.google.com</td>
 <td></td>
</tr>

</tbody></table>
</body>
</html>

2.Create second test case
Test2.html
==========

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Propagate_Negative_API_UK</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Propagate_Negative_API_UK</td></tr>
</thead><tbody>
<!------------------ Initialization steps ---------->
<tr>
 <td>store</td>
 <td>varaible from first test2</td>
 <td>vartest2</td>
</tr>

<tr>
 <td>open</td>
 <td>http://www.yahoo.com</td>
 <td></td>
</tr>
<tr>
 <td>echo</td>
 <td>${vartest1}</td>
 <td></td>
</tr>

3.Create third test case
Test3.html
=========

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Propagate_Negative_API_UK</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Propagate_Negative_API_UK</td></tr>
</thead><tbody>
<!------------------ Initialization steps ---------->
<tr>
 <td>store</td>
 <td>varaible from first test3</td>
 <td>vartest3</td>
</tr>

<tr>
 <td>open</td>
 <td>http://www.gmail.com</td>
 <td></td>
</tr>
<tr>
 <td>echo</td>
 <td>${vartest2}</td>
 <td></td>
</tr>
</tbody></table>
</body>
</html>

4.Create test suite
TestSuite.html
=========


<html>
 <head></head>
  <body>
   <table>
    <tbody>

     <tr>
       <td>Test suite for sharing variable among test cases </td>
     </tr>

     <tr>
      <td><a target="testFrame" href="test1.html">test1</a></td>
     </tr>

    <tr>
      <td><a target="testFrame" href="test2.html">test2</a></td>
    </tr>

    <tr>
      <td><a target="testFrame" href="test3.html">test3</a></td>
    </tr>
  </tbody>
</table>
</body>
</html>


Run your test suite and you will see the variable vartest1 decalred in testcase1 being used in testcases2
and variable vartest2 declared in testcase2 being used in testcase3.

Files are attached here . Right click on this link and save as ...
  Download test case and suite

How to use functions in xpath in selenium

How to use functions in xpath
Automation using selenium is a great experience. It provides many way to identif an object or element on the web page.
But sometime we face the problems of idenfying the objects on a page which have same attributes. When we get more than
one element which are same in attribute and name like multiple checkboxes with same name and same id. More than one button having
same name and ids. There are no way to distingues those element. In this case we have problem to instruct selenium to identify a perticular
object on a web page.
I am giving you a simple example . In the below html source there are 6 checkboxes are there having same type and same name.
It is really tough to select third or fifth.

<html>
<body>
<input type='checkbox' name='chk'>first
<br><input type='checkbox' name='chk'>second
<br><input type='checkbox' name='chk'>third
<br><input type='checkbox' name='chk'>forth
<br><input type='checkbox' name='chk'>fifth
<br><input type='checkbox' name='chk'>sixth
</body>
</html>


Thare are some function we can use in Xpath to identify the abject in above cases.
An XPath expression can return one of four basic XPath data types:

* String
* Number
* Boolean
* Node-set

XPath Type : Functions
Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()
String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-space(), translate()
Boolean : boolean(), not(), true(), false(), lang()
Number : number(), sum(), floor(), ceiling(), round()

I will show you how we can use some of these above functions in xpath to identify the objects.

Node Set : last()


In the above html file there are six checkboxes and all are having same attributes (same type and name)
How we can select the last checkbox based on the position. We can use last() function to indentify the last object among all similar objects.
Below code will check or uncheck the last checkbox.

selenium.click("xpath=(//input[@type='checkbox'])[last()]");

How we can select the second last checkbox and third last checkbox. We can use last()- function to indentify the last object among all similar objects.
Below code will check or uncheck the second last checkbox and thrid last checkbox respectively.

selenium.click("xpath=(//input[@type='submit'])[last()-1]");
selenium.click("xpath=(//input[@type='submit'])[last()-2]");


Node Set : position()

If you want to select any object based on their position using xpath then you can use position() function in xpath.
You want to select second checkbox and forth checkbox then use below command

selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");
selenium.click("xpath=(//input[@type='checkbox'])[position()=4]");

above code will select second and forth checkbox respectively.

String : starts-with()

Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically.
Each time id gets generated differently. So to handle this situation we use some JavaScript functions.

XPath: //button[starts-with(@id, 'continue-')]  


Sometimes an element gets identfied by a value that could be surrounded by other text, then contains function can be used.
To demonstrate, the element can be located based on the ‘suggest’ class without having
to couple it with the ‘top’ and ‘business’ classes using the following

XPath: //input[contains(@class, 'suggest')].



For rest of the function please keep reading my blogs i will be posting very soon.

Tuesday, August 24, 2010

How to handle Selenium is already running on port 4444

When we run selenium RC test cases sometimes we faces this issue saying "java.net.BindException: Selenium is already running on port 4444. Or some other service is." When you check the port 4444 no service is running. We change the port and run the program even that too is not working.
In these cases we need to shutdown the selenium server on this port.
Use below command to shut down the server.

http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer

If selenium server is already running on port 4444 then it will shut down the server and says
OKOK
if selenium is not running on this port 4444 then by hitting above url will give you
"Unable to connect"
Now you can run your test cases i am sure will run smoothing.

How to get browser name, version and operating system detail in selenium

We can get the browser name, version and operating system name and version with the following commands in selenium RC.
Below code is tested in Mozilla Firefox
Browser Name

System.out.println(selenium.getEval("navigator.appCodeName;"));

Mozilla

Browser version

System.out.println(selenium.getEval("navigator.appVersion;"));

5.0 (Windows; en-US)

Browser and Operating system detail

System.out.println(selenium.getEval("navigator.userAgent;"));

Result.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 (.NET CLR 3.5.30729)

String browser = selenium.getEval("navigator.userAgent");
if (browser.contains("Firefox")  || browser.contains("Chrome")) {


Thursday, August 19, 2010

How to verify html source in selenium

We can verify the html source with selenium commands

<html>
<head>
<title>HTML Source</title>
</head>
<body>
what need to be verifed Text is here we need to verify
</body>
</html>

Script


verifyTrue(selenium.getHtmlSource().matches("^[\\s\\S]*Text is here[\\s\\S]*$"));

above command will verify Text is here in above html srource

verifyTrue(selenium.getHtmlSource().matches("^[\\s\\S]*Text i here[\\s\\S]*$"));

above command will fail because it tries to verify Text i here which is not there in html source

How to handle the input promt dialog in selenium

There are some scenarios where we need to input when our web application need external input data by opening input prompt dialog box. To handle these dialog boxes in automation is tricky task. We can handle these situation with below codes.
Html file is at the bottom

selenium.open("Input_prompt_TestCase.html");

Verify there is no input dilog present while opening this file


assertTrue(!selenium.isPromptPresent());

When then Input prompts select NO first time by the command answerOnNextPrompt|no|

selenium.answerOnNextPrompt("no");

Now click to open the input dialog by clicking the link "Click here to open input dialog"

selenium.click("promptdialog");

Now verify prompt presents or not with the command verifyPromptPresent||
assertTrue(selenium.isPromptPresent());
If it takes time to open the prompt then we can wait till 1 minute with the below code.

boolean Bool = false;
for (int second = 0; second < 60; second++) { 
try { 
if ((selenium.isPromptPresent())) {
Bool = true;
break; 
}
}
catch (Exception ignore) {
}
pause(1000);
}
assertTrue(Bool);


Now after 1 minute verify the prompt presents or not with the command assertPromptPresent||


assertTrue(selenium.isPromptPresent());

If it verifies prompt is there then verify the text what is on prompt with the command
verifyPrompt|Type 'automationtricks' and click OK|


verifyEquals("Type 'automationtricks' and click OK", selenium.getPrompt());

You can also verify the title of input prompt with the command verifyTitle|Test Prompt|


verifyEquals("*Testcases for input Prompt", selenium.getTitle());

Now you just enter automationtricks in input promt with this command
answerOnNextPrompt|automationtricks|


selenium.answerOnNextPrompt("automationtricks");

and then click on ok with command clickAndWait|promptdialog|


selenium.click("promptdialog");

Now you can see the result based on your input


selenium.waitForPageToLoad("5000");
verifyTrue(selenium.isTextPresent("You have entered automationtricks!"));



For Selenium IDE user : How to handle prompt in selenium IDE


<tr>
<td>open</td>
<td>Input_prompt_TestCase.html</td>
<td></td>
</tr>
<tr>
<td>answerOnNextPrompt</td>
<td>automationtricks</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>promptdialog</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>You have entered automationtricks!</td>
<td></td>
</tr>
<tr>
<td>open</td>
<td>Input_prompt_TestCase.html</td>
<td></td>
</tr>
<tr>
<td>answerOnNextPrompt</td>
<td>niraj</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>promptdialog</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>You have not entered automationtricks!</td>
<td></td>
</tr>


For the above code find Html file below


<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html">
<script type="text/javascript">
function opendialog() {
if (prompt("Type 'automationtricks' and click OK") == 'automationtricks') {
document.write("You have entered automationtricks!");
}
else{
document.write("You have not entered automationtricks!");
}
}
</script>
<title>Testcases for input Prompt</title>
</head>
<body>
<img style="width: 644px; height: 41px;" alt="banner" src="banner.gif"><br>
<a id="promptdialog" href="javascript:opendialog();">Click here to open input dialog</a>
</body>
</html>


Wednesday, August 18, 2010

How to create test suite using Junit and eclipse in selenium

There are some scenarios where we need to run multiple test cases. Either we can run those test cases independently or together. But there are some real time cases where we need to run our test cases in a particular order. In this case we would prefer Test Suite to combine the test cases together and decide their orders and run those.


Below are the steps

1. Create a Test Suite class where we create the Test Suites which will call all the test cases in a particular order.

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;  
import junit.textui.TestRunner;

public class TestSuite1 extends TestCase {

public static Test suite()  
{  
TestSuite suite = new TestSuite();  

suite.addTestSuite( TestCase1.class);  
suite.addTestSuite( TestCase2.class);
suite.addTestSuite( TestCase3.class);  
return suite;  
}  

public static void main(String arg[])
{
TestRunner.run(suite());

}
}


Step 2. Create your first test case

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase1 extends SeleneseTestCase{

Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;

public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();

}
public void testgoogling() {
selenium.open("/");
selenium.type("q", "Niraj");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Niraj"));

}

public void tearDown() throws InterruptedException{
selenium.stop(); 
seleniumServer.stop();
}
}

Step 3. Create your second test case

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase2 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}

public void testgoogling() {
selenium.open("/");
selenium.type("q", "Niraj Kumar");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("Niraj Kumar"));

}

public void tearDown() throws InterruptedException{
selenium.stop(); 
seleniumServer.stop();
}
}


Step 4. Create your third test case

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.*;
public class TestCase3 extends SeleneseTestCase{
Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS="60000";
private SeleniumServer seleniumServer;
public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();
rc.setSingleWindow(true);
seleniumServer = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com/");
seleniumServer.start();
selenium.start();
}

public void testgoogling() {
selenium.open("/");
selenium.type("q", "http://www.automationtricks.blogspot.com");
selenium.click("btnG");
selenium.waitForPageToLoad(MAX_WAIT_TIME_IN_MS);
assertTrue(selenium.isTextPresent("http://www.automationtricks.blogspot.com"));

}

public void tearDown() throws InterruptedException{
selenium.stop(); 
seleniumServer.stop(); 
}
}

Step 5. Run your Test Suite
Go to your Test Suite class and right click on that and run as Junit Test.

This will run the TestCase1 then TestCase2 then TestCase3


If you want to execute your test cases in some specific order then you call them in that order like.

suite.addTestSuite( TestCase3.class);  
suite.addTestSuite( TestCase2.class);
suite.addTestSuite( TestCase1.class);  

Above will run the TestCase3 first then TestCase2 then TestCase1.

Monday, July 19, 2010

How to store date in dd-mm-yy format in Selenium

There are some cases while we search the data based on start and end date based on date format dd-mm-yy.

=======

<tr>
<td>store</td>
<td>javascript{var d = new Date();var curr_date = d.getDate()-2;if(curr_date.toString().length!=2) curr_date = '0'+curr_date ;var curr_month = d.getMonth(); curr_month = curr_month + 1;if(curr_month.toString().length!=2) curr_month= '0'+curr_month;curr_date + '-'+ curr_month + '-'+10;}</td>
<td>start_date</td>
</tr>
<tr>
<td>store</td>
<td>javascript{var d = new Date();var curr_date = d.getDate();if(curr_date.toString().length!=2) curr_date = '0'+curr_date ;var curr_month = d.getMonth(); curr_month = curr_month + 1;if(curr_month.toString().length!=2) curr_month= '0'+curr_month;curr_date + '-'+ curr_month + '-'+10;}</td>
<td>end_date</td>
</tr>
<tr>
<td>echo</td>
<td>${start_date}</td>
<td></td>
</tr>
<tr>
<td>echo</td>
<td>${end_date}</td>
<td></td>
</tr>


This gives the result in below format
Start date : 17-07-10
End date : 19-07-10


Saturday, June 5, 2010

How to get current page url in selenium

There are some situations where we need to know the url of current page.

selenium IDE

<tr>
<td>storeLocation</td>
<td>url</td>
<td></td>
</tr>
<tr>
<td>echo</td>
<td>${url}</td>
<td></td>
</tr>



Selenium RC

String url = selenium.getLocation();
System.out.println(url);

Saturday, May 22, 2010

Selenium Regular Expression and pattern matching

Like locators, patterns are a type of parameter frequently required by Selenese commands. Examples
of commands which require patterns are verifyTextPresent, verifyTitle, verifyAlert, assertConfirmation,
verifyText, and verifyPrompt.Patterns allow one to describe, via the use of special characters, what text is expected rather
than having to specify that text exactly

  • Global Patterns

    * which translates to “match anything,” i.e., nothing, a single character, or many characters.
    [ ] (character class) which translates to “match any single character found inside the square
    brackets.” A dash (hyphen) can be used as a shorthand to specify a range of characters
    (which are contiguous in the ASCII character set). A few examples will make the functionality
    of a character class clear:
    [aeiou] matches any lowercase vowel
    [0-9] matches any digit
    [a-zA-Z0-9] matches any alphanumeric character
    In most other contexts, globbing includes a third special character, the ?. However, Selenium globbing
    patterns only support the asterisk and character class.
    To specify a globbing pattern parameter for a Selenese command, one can prefix the pattern with a glob:
    label. However, because globbing patterns are the default, one can also omit the label and specify just
    the pattern itself.
    Below is an example of two commands that use globbing patterns. The actual link text on the page
    being tested was “Film/Television Department”; by using a pattern rather than the exact text, the click
    command will work even if the link text is changed to “Film & Television Department” or “Film and
    Television Department”. The glob pattern’s asterisk will match “anything or nothing” between the word
    “Film” and the word “Television”.
    click link=glob:Film*Television Department
    verifyTitle glob:*Film*Television*
    The actual title of the page reached by clicking on the link was “De Anza Film And Television Department
    - Menu”. By using a pattern rather than the exact text, the verifyTitle will pass as long as
    the two words “Film” and “Television” appear (in that order) anywhere in the page’s title. For example,
    if the page’s owner should shorten the title to just “Film & Television Department,” the test would still
    pass. Using a pattern for both a link and a simple test that the link worked (such as the verifyTitle
    above does) can greatly reduce the maintenance for such test cases.

    Some examples for global pattern

    Lets say your element looks like

    <input class="foo" value="the text value" name="theText">

    verifyEquals("*text*", selenium.getValue("theText"));

    <input type="hidden" value="the hidden value" name="theHidden">

    verifyEquals("* hidden value", selenium.getValue("theHidden"));

    If you have drop down combo box then you can use global pattern matching .

    <select id="theSelect">
    <option id="o1" value="option1">first option</option>
    <option selected="selected" id="o2" value="option2">second option</option>
    <option id="o3" value="option3">third,,option</option>
    </select>

    select the second option and verify like this

    assertEquals("second *", selenium.getSelectedLabel("theSelect"));
    or,
    String[] arr = {"first*", "second*", "third*"};

    verifyEquals(arr, selenium.getSelectOptions("theSelect"));

  • The question mark ? indicates there is zero or one of the preceding element. For example, colo?r matches both "color" and "colour".

    If your element is like
    <input class="foo" value="the text value" name="theText">

    verifyEquals("?oo", selenium.getAttribute("theText@class"));


  • Regular expression
    Regular expression patterns are the most powerful of the three types of patterns that Selenese supports.
    Regular expressions are also supported by most high-level programming languages, many text editors and a host of tools, including the Linux/Unix command-line utilities grep, sed, and awk.

    regexp (wildcard) matching


    <input class="foo" value="the text value" name="theText">

    verifyEquals("regexp:^[a-z ]+$", selenium.getValue("theText"));

    <input type="hidden" value="the hidden value" name="theHidden">

    verifyEquals("regexp:dd", selenium.getValue("theHidden"));


    <select id="theSelect">
    <option id="o1" value="option1">first option</option>
    <option selected="selected" id="o2" value="option2">second option</option>
    <option id="o3" value="option3">third,,option</option>
    </select>

    assertEquals("regexp:second .*", selenium.getSelectedLabel("theSelect"));

  • verify Attributes using regular expression

    <input class="foo" value="the text value" name="theText">

    verifyEquals("regexp:^f", selenium.getAttribute("theText@class"));

    verifyEquals("regex:^[a-z ]+$", selenium.getValue("theText"));

    <select id="theSelect">
    <option id="o1" value="option1">first option</option>
    <option selected="selected" id="o2" value="option2">second option</option>
    <option id="o3" value="option3">third,,option</option>
    </select>

    assertEquals("exact:second option", selenium.getSelectedLabel("theSelect"));

    String[] arr = {"regexp:^first.*?", "second option", "third*"};
    verifyEquals(arr, selenium.getSelectOptions("theSelect"));
  • How to test element is editable in selenium

    We can verify weather an element is editable or not using isEditable selenium command.

    If your element is in below format
    
    <input value="black" name="plain_text">
    
    
    then we can use selenium isEditable to find this element is editable or not
    
    assertTrue(selenium.isEditable("plain_text"));
    
    <select name="plain_select"><option>Niraj</option></select>
    
    assertTrue(selenium.isEditable("plain_select"));
    
    <input disabled="yup" value="black" name="disabled_text">
    
    assertTrue(!selenium.isEditable("disabled_text"));
    
    <select disabled="yup" name="disabled_select"><option>Niraj</option></select>
    
    assertTrue(!selenium.isEditable("disabled_select"));
    
    

    How to test based on attributes of element using CSS

    We can test based on attributes of elements by using css. We can use regular expression in css attributes to identify the element.
    If your element is in this css format.
    
    <div id="css3test"><a name="foobar">foobar</a><a name="barfoo">barfoo</a><a id="foobar" name="foozoobar">foozoobar</a></div>
    
    
  • How to store the text of and element which css attributes start with some specific letters.

    Ex. in above element how to store the text whose element name start with "foo"
    Selenium IDE
    
    
    <tr>
    <td>storeText</td>
    <td>css=a[name^="foo"]</td>
    <td>str</td>
    </tr>
    
    
    Selenium RC
    
    String str = selenium.getText("css=a[name^=\"foo\"]");
    
    
    This will store the "foobar" in str variable because element <a name="foobar">foobar</a> name start with "foo"

  • How to store the text of and element which css attributes ends with some specific letters.

    Ex. in above element how to store the text whose element name ends with "foo"

    Selenium IDE
    
    <tr>
    <td>storeText</td>
    <td>css=a[name$="foo"]</td>
    <td>str</td>
    </tr>
    
    
    Selenium RC
    
    String str = selenium.getText("css=a[name$=\"foo\"]");
    
    
    This will store the "barfoo" in str variable because element <a name="barfoo">barfoo</a> name ends with "foo"

  • How to store the text of and element which css attributes starts with any letters and ends with any letters but containing some specific letters in middle.

    Ex. in above element how to store the text whose element name ends with any letter and ends with any letter but containing some specific letters "zoo"

    Selenium IDE
    
    <tr>
    <td>storeText</td>
    <td>css=a[name*="zoo"]</td>
    <td>str</td>
    </tr>
    
    

    Selenium RC
    
    String str = selenium.getText("css=a[name*=\"zoo\"]");
    
    
    This will store the "foozoobar" in str variable because element <a name="foozoobar">foozoobar</a> name contains "zoo" in the middle.

    There is another method to store
    
    String str = selenium.getText("css=a:contains(\"zoo\")");
    
    

  • How to identify element using more than one css attributes.

    Lets say your element is in this format.
    
    <a alt="foo" class="a2" href="#id2" name="name1" id="id2">this is the <b>second</b> <span selenium:foo="bar">element</span></a>
    
    
    then if you want to store "this is the second element" in a variable called str the

    Selenium IDE
    
    <tr>
    <td>storeText</td>
    <td>css=a[name*="name"][alt="foo"]</td>
    <td>str</td>
    </tr>
    
    
    Selenium RC
    
    String str = selenium.getText("css=a[name*=\"name\"][alt=\"foo\"]");
    
    
    If you want to store only "element" from above element then use below code
    Selenium IDE
    
    <tr>
    <td>storeText</td>
    <td>css=a[name*="name"][alt="foo"]>span</td>
    <td>str</td>
    </tr>
    
    
    Selenium RC
    
    String str = selenium.getText("css=a[name*=\"name\"][alt=\"foo\"]>span");
    
    
  • How to test Pseudo-classes : Pseudo-elements and pseudo-classes

    Lets say your element looks like
    
    <div id="structuralPseudo">
    <span>span1</span>
    <span>span2</span>
    <span>span3</span>
    <span>span4</span>
    <div>div1</div>
    <div>div2</div>
    <div>div3</div>
    <div>div4</div>
    </div>
    
    
    to identify the element within the element we will use
    
    css=div#structuralPseudo :nth-child(n)
    
    

    1. To identify first element in pseudo element id="structuralPseudo and store its text.
    
    String str = selenium.getText("css=div#structuralPseudo :nth-child(n)");
    
    
    this will store "span1" in str variable.

    2. To identify second element in pseudo element id="structuralPseudo and store its text.
    
    String str = selenium.getText("css=div#structuralPseudo :nth-child(2n)");
    
    
    this will store "span2" in str variable.

    3. To identify third element in pseudo element id="structuralPseudo and store its text.
    
    String str = selenium.getText("css=div#structuralPseudo :nth-child(3n)");
    
    
    this will store "span3" in str variable.
    ...
    ...
    ...

    8.. To identify the last element in pseudo element id="structuralPseudo and store its text.
    
    String str = selenium.getText("css=div#structuralPseudo :nth-child(3n)");
    
    
    this will store "div4" in str variable.


    9. But you can access first and last child directly

    to access first element
    
    String str = selenium.getText("css=div#structuralPseudo :first-child");
    
    
    this will store "span1" in str variable
    To access last element
    
    String str = selenium.getText("css=div#structuralPseudo :last-child");
    
    
    this will store "div4" in str variable
    For more details about css selector please visit .

    http://www.w3.org/TR/CSS2/selector.html

    
    <input type="text" disabled="true" value="disabled" name="disabled">
    
    assertTrue(selenium.isElementPresent("css=input[type=\"text\"]:disabled"));
    
    <input type="checkbox" checked="true" value="checked" name="checked">
    
    assertTrue(selenium.isElementPresent("css=input[type=\"checkbox\"]:checked"));
    
    

  • Friday, May 21, 2010

    How to test the immediate element using CSS


    We can test the elements and their immediate elements using CSS.
    If your element is in this format.
    
    <span id="firstChild">first child <a>second child</a></span>
    
    
  • How to store "first child" in a variable called str then use
    
    String str = selenium.getText("css=div#combinatorTest > span");
    
    
  • If you need to store the text of immediate element <a>second child</a> in a variable called str then use

    
    String str = selenium.getText("css=div#combinatorTest > span>a");
    
    
  • If you element has many value in its class then you can identify the element or you can store the element text in a variable

    <a class="class1 class2 class3">this is the element</a>

    You can use below code for verifying the element or storing the text in the element.
    Verifying element in RC
    
    verifyTrue(selenium.isElementPresent("css=a[class~=\"class2\"]"));
    
    
    Verifying element in IDE
    
    <tr>
    <td>verifyElementPresent</td>
    <td>css=a[class~="class2"]</td>
    <td></td>
    </tr>
    
    

    storing element text in a variable using RC
    
    String str = selenium.getText("css=a[class~=\"class3\"]");
    
    
    storing element text in a variable using IDE
    
    <tr>
    <td>storeText</td>
    <td>css=a[class~="class3"]</td>
    <td>str</td>
    </tr>
    
    
  • Testing preceding combinator elements

    
    <div id="combinatorTest">this is the parent element. <span id="firstChild">this is a child element <a>and grandson element</a></span>, <span>another child element</span>, <span>last child element<span></span></span></div>
    
    
    How to store the text of preceding combinator element in RC

    to store "another chile element"
    
    String str = selenium.getText("css=span#firstChild + span");
    
    
    to store "last child element"
    
    String str = selenium.getText("css=span#firstChild + span + span");
    
    
    How to store the text of preceding combinator element in IDE

    to store "another chile element"
    
    <tr>
    <td>storeText</td>
    <td>css=span#firstChild + span</td>
    <td>str</td>
    </tr>
    
    
    to store "last child element"
    
    <tr>
    <td>storeText</td>
    <td>css=span#firstChild + span + span </td>
    <td>str</td>
    </tr>