July 12, 2016

Perfect Example for Handling Window,popup,Frame and Alerts

In this post i will explain about how to handle

  1. Multiple windows
  2. Popups
  3. Tabs
  4. Frames
  5. Alerts
and how to write customized functions, instead of duplicating the webdriver code.

Here is one example to switchToChildWindow()
This method is useful to switch to new window/tab/popup if you have only 2 windows/tabs/popup then you can use below customized function.



In the below example i wrote different functions 

  1.  isElepresent(By locator) -- Verify if the element is present or not
  2. selectByText(By locator, String visibleText) select a value from dropdown
  3. switchToChildWindow() ---Switch to  child window. If there are only two windows.
  4. switchToWindowByTitle(String title)  ---Switch to child window. Use this if title of the pages are unique.
  5. switchToFrame(WebElement locator)  --switch to frame by locating the frame.


Scenario: which has all multiple windows/tabs/popups/alerts/frames etc...

  1. Open http://www.hdfcbank.com/
  2. Close the Ad window if that is visible
  3. Click on Agri Link --which will open new window/tab
  4. Select "Telugu" from dropdown
  5. Handle the alert
  6. Select "English" from dropdown
  7. Click on Account Details --which will open new window/tab
  8. In the new window, enter customer ID --"test" (Actually this text box is in frame)
  9. Click on Privacy Policy link (Actually this link is in another frame) --which opens new window/tab/popup
  10. Click on CSR link on Privacy Policy page.
  11. Now come back to Main window (Parent window) 
  12. Click on Customer Care.

Below is the code:







Read more ...

June 13, 2016

Handling OnChange events using Selenium webdriver and Java script

In this post I will discuss about onchange events.

What is onchange event?
The onchange event occurs when the value of an element has been changed.
For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

onChange specifies script code to run when the data in the input field changes. The onChange event is triggered when the contents of the field changes.

In this example if you type some thing in Quantity filed and click on anywhere on the page it will automatically update Total.








We can handle onchange events in different ways.

1. After entering quantity we can simulate clicking TAB button. But this is approach will not work always.

2. By using Java script we can trigger onchange event.


Using Java script to trigger onchange event...


((JavascriptExecutor)driver).executeScript("arguments[0].onchange()", driver.findElement(By.name("vn_qty")));

Below is the sample script.










Read more ...

March 3, 2016

Advanced Xpath with Examples

Here i am going to discuss about advanced usage of xpaths..
I will provide examples how to use xpath Axes.

Descendants
A node's children, children's children, etc.
In the following example; descendants of the form element are the div, title, author, year, and price elements


<form>

<div>
  
<title>Harry Potter</title>
  
<author>J K. Rowling</author>
  
<year>2005</year>
  
<price>29.99</price>
</div>

</form>


Here is Example:





If you want to find descendants of Div tag you need to use below syntax

//div[@id='browse-category']/descendant::*

If you want a specific element from descendants then use below syntax

Here i want to identify Payment link using descendant.

//div[@id='browse-category']/descendant::a[@data-category='Payment']

In the above example descendant will search for child elements and child's child elements as well.

UL is the child element for DIV and LI is the child element for UL and A is child element for LI. As we used descendant it will check for the matching element.



Following:
Selects everything in the document after the closing tag of the current node.


selects all elements after closing tag of P

//p[@class='fk-font-14']/following::*




if you want a specific element using following below is the example

//p[@class='fk-font-14']/following::div[@id='fk-mainfooter-id']


Following-sibling:
Selects all siblings after the current node.
//div[@id='browse-category']/ul/li/following-sibling::*

if you want a specific element then

//form[@class='faqsearchform']/following-sibling::div





Preceding :
Selects all nodes that appear before the current node in the document, except ancestors, attribute nodes and namespace nodes

preceding-sibling
Selects all siblings before the current node

Here is the example:

//div[@id='browse-category']/preceding-sibling::form





Now Lets see a real time example how to use the above mentioned xpath Axes:

Below is scenario:


  1. Navigate to flipkart
  2. add two products to cart
  3. I want to remove one product based on its name.




Simple xpath without using product name --- //a[@class='cart-remove-item fk-inline-block fk-uppercase'] but it always identifies first Remove button.


First Step: I will identify xpath for product Name

//span[text()='HP 15-af114AU Notebook(AMD Quad Core A8/ 4GB/...']

From there onward using xpath Axes i need to identify Remove link.

By loooking at DOM we can understand that there are two TR tags 
in one TR --we have product details and in another TR we have remove link.

so i have to traverse to second TR.

Second Step: Inorder to do that i need to traverse to parent element of span

//span[text()='HP 15-af114AU Notebook(AMD Quad Core A8/ 4GB/...']/ancestor::tr[1]

Third Step: from there traverse to sibling of TR
//span[text()='HP 15-af114AU Notebook(AMD Quad Core A8/ 4GB/...']/ancestor::tr[1]/following-sibling::tr

Fourth Step: From there traverse to tag A which has link text of Remove..here is the final xpath

//span[text()='HP 15-af114AU Notebook(AMD Quad Core A8/ 4GB/...']/ancestor::tr[1]/following-sibling::tr
/descendant::a[text()='Remove']


Hope this is useful in writing advanced xpaths....if you have any questions please do comment and I will be happy to help in you in writing xpaths..







Read more ...

October 30, 2015

Run selenium tests in Chrome and IE browser

How to run the selenium test scripts in Chrome/IE browser ?

To run the selenium test cases in Chrome/IE browser is necessary and need of today's web world as Chrome being the one of the best and most widely used web browser.

Selenium by default supports only Mozilla Firefox . 

To run your tests in Chrome browser please do the following set-up.

1. Download chrome browser related jar file from here.

2. Set the System configuration by adding the following code.

System.setProperty("webdriver.chrome.driver", "Path to chrome related jar file downloaded in step 1");
WebDriver driver = new ChromeDriver();

To run the test in Internet explorer.

1. Download IE browser related jar file from here.

2. Set the System configuration by adding the following code.

System.setProperty("webdriver.ie.driver", "C:\\Users\\ajain5\\Downloads\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();



Read more ...

October 20, 2015

Handling Basic Authentication Using Webdriver

Here is post which explains you how to handle basic authentication.

Problem:

Some of the applications that are secured with Basic Authentication. If you want to access those applications first you need to pass credentials. Those applications will launch a system level pop-up which cant not be handled by selenium.

IF you access below url it will ask for authentication.

http://the-internet.herokuapp.com/basic_auth



Solution:

By specifying userName and password in URL when accessing the page we can avoid system level dialog. This approach will work for HTTP and HTTPS pages.


Reference: http://elementalselenium.com/tips/13-work-with-basic-auth

Example:

Read more ...

October 8, 2015

Selenium Integration With Jenkins

In this post i am going to explain how to integrate with continuous integration tool Jenkins..

Prerequisites:
Here i am trying to run Maven project scripts so

  1. Maven Project with TestNG (you can go through this post  create-sample-maven-project.html)
  2. and few webdriver scripts
  3. Downlaod Maven Project from Here....
Download Jenkins:

1. Navigate ti http://jenkins-ci.org/
2. Download .war file

3. Save the jenkins.war file in any of the location, you need to run this Jenkins.war file.


Set Up Jenkins:

1. Navigate to folder where you kept your jenkis.war
2. type command java -jar jenkins.war and press Enter

3. Will take some time to extract Jenkins, then you will get a success message.
4. By default Jenkins will start in port number 8080
5. For Jenkins UI use this URL in browser http://localhost:8080/



Configure Jenkins:

Before creating any Jenkins job we need to perform some configuration steps.
1. Click on Manage Jenkins link on the left side of the page
2. Click on Configure System.
3. Navigate to JDK section and Click on Add JDK button
4. Uncheck Install automatically check box so Jenkins will only take java which we have mention above
5. Give the name as JAVA_HOME and Specify the JDK path


6. Add Maven. IF you already not downloaded maven, get it from here Download Maven


6. Click on Save button.


Create Jenkins Job:
1. Click on create new Jobs.
2. Enter Job description and select Maven Project
3. Go to Build section and Enter path of POM.xml in ROOT POM text box.
4. Click apply and Save,



Run Job:
Navigate to Home page of Jenkins, there you can see new Job is created. Click on Build now symbol

Maven will build the project. It will then have TestNG execute the test cases
Once the build process is completed, in Jenkins Dashboard click on the Job1 project






Read more ...

October 7, 2015

Log4J Configuration

In this post i will discuss about Log4J and Log files.

Log file is just simple file, which keep track of the record or event or info when any event happens or any software run. This whole process known as logging. We can create log file as simple log file.

Why Log file is required:

We can create log file for our simple script also so we can track or debug our script easily if anything goes wrong in script. For example, if our script is failing at some point then we can track back what went wrong

What is log4J
Log4j is free open source tool  for creating log files It help us to generate log file.

Log4j is very lightweight and simple logging framework, comprising of three main components
Loggers
Appenders
Layouts

Download Log4J jar file.

1. Navigate to http://mvnrepository.com/
2. Search for Log4J
3. Download latest version of log4J




Create a sample Java project and add log4J. jar file to project.

Create a properties file 
Right click on Project --New --File
give a name log4j.properties.
and add below code in that file






Create a Class file with below log levels:


logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");

Below is the sample code:



After executing test you can see logs in log4j.log file and in console as well.






OUTPUT of Log4J file:



Read more ...

October 2, 2015

Handling webtables

This post explains about Handling Webtables.

Get Number of Columns
Get Number of Rows
Get Content of a specific cell based on Row and Column value.

Below is the code:



Read more ...

September 28, 2015

isDisplayed vs isEnabled

In this post i will  show you the difference between isDisplayed() and isEnabled()


isDisplayed

boolean isDisplayed()
Is this element displayed or not? This method avoids the problem of having to parse an element's "style" attribute.
Returns:
Whether or not the element is displayed

Method used to verify presence of a web element within the webpage. The method is designed to result a Boolean value with each success and failure. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.


isEnabled

boolean isEnabled()
Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
Returns:
True if the element is enabled, false otherwise.

Reference :  https://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#isEnabled()
Method used to verify if the web element is enabled or disabled within the webpage. Like isDisplayed() method, it is designed to result a Boolean value with each success and failure. The method returns a “true” value if the specified web element is enabled on the web page and a “false” value if the web element is not enabled (state of being disabled) on the web page






After Executing code :







Below is the Code:





Read more ...

September 16, 2015

Selenium Grid Extras

In this post i am going to explain about Selenium Grid Extras.

Selenium Grid Extras :

Simplify the management of the Selenium Grid Nodes and stabilize said nodes by cleaning up the test environment after the build has been completed.

For More information on Selenium Grid Extras you can refer to this link. 

Selenium-Grid-Extras



Features of Grid Extras:
  • Ability to control individual grid nodes, following is an incomplete list of OS level tasks:
    • Killing any browser instance by name
    • Stopping any Process by PID
    • Moving mouse to specific location
    • Get Memory usage and disk statistics
  • Automatically upgrade WebDriver binaries
  • Restart node after a set number of test executions
  • Central storage of configurations for all nodes on the HUB server
  • Screenshots at the OS level
  • And much more.


Steps to Install / Configure Selenium Grid Extras:

Download Grid Extras Jar file from Here : Download Selenium-Grid-Extras

Selenium Grid Extras is a project that helps you set up and manage your local Selenium Grid. Typical instances of the Grid consists of the HUB and Nodes. The HUB is responsible for managing test sessions and assigning new session idle nodes.
Setup of Grid Extras is made to be simple, just run the packaged JAR file and point the node at the HUB location, Grid Extras will take care of the rest for you.

Hub SetUp:
1. After downloading selenium grid extras jar file, open command prompt and navigate to folder where grid extras jar file is available.
2. Type in command  java -jar


I renamed selenium grid extras jar file to SeleniumGridExtras.jar.

After starting seleniumgridextras it will prompt several questions.

What is the default Role of this computer? (1 - node | 2 - hub | 3 - hub & node)

Default Value: 1

if you want to use your machine as Hub..then you need to type 2, if you want to use your machine as hub and node then type 3.

In this case i am using it as hub  so i type in 2.

What is the HOST for the Selenium Grid Hub?
Default Value: 127.0.0.1
In my case it is default value so i just click Enter

What is the PORT for the Selenium Grid Hub?
Default Value: 4444
Press Enter port will be set to 4444


What is node Platform? (WINDOWS|XP|VISTA|WIN8|WIN8_1|MAC|LINUX|UNIX|ANDROID)
Default Value: VISTA

I left it as default

Would you like WebDriver, IEDriver and ChromeDriver to auto update (1-yes/0-no)
Default Value: 1
Press Enter --it will automatically updte your webdriver,IE and chrome drivers

Once you set all options your command prompt should look like this



Verify Grid Console and Grid Extras

type in the IP address which is shown in command prompt and output looks like this




It shows you  RAM and OS details

Now open grid console --- http://localhost:4444/grid/console




Grid Node Set Up:

Go to another machine and start seleniumgridExtras.jar

It will prompt several questions:

What is the default Role of this computer? (1 - node | 2 - hub | 3 - hub & node)

Default Value: 1
type 1 ..bcs we want to use this as node


What is the HOST for the Selenium Grid Hub?
Default Value: 127.0.0.1
type in IP address of HUB ..ex: 172.xx.xx.xx

What is the PORT for the Selenium Grid Hub?
Default Value: 4444
Press Enter port will be set to 4444


Will this node run 'Firefox' (1-yes/0-no)
Default Value: 0

Yes I want to run Firefox so i type in 1

What version of 'Firefox' is installed?
Default Value: 36

It will identify your firefox version. Press Enter

Will this node run 'InternetExplorer' (1-yes/0-no)
Default Value: 0
Yes I want to run IE so i type in 1

Similarly it will prompt questions for Chrome, Safari based on your requirement you have to choose option.

Would you like this Node to auto update browser versions? (1-yes/0-no)
Default Value: 1

press 1 if you want to auto update browser versions.



Should this Node record test runs? (1-yes/0-no)
Default Value: 1

Press Enter 


Once you set all the options it will start Grid Extras..

it should look like this....


Now you are all set to run your scripts on grid extras.

Again come back to HUB and navigate to http://localhost:4444/grid/console 
it should look like this







Now i can run scripts in FF,IE and Chrome.

The rest is same..you have to run your webdriver script.

Below is the sample script.




Once the execution is done...Open HUB URL http://1xx.xx.xx.xx:3000/ or in HUB machine open url 

It should look like this...



You can see videos in seleniumgrid extras folder...where you seleniumgridextras jar file is available. One folder will be created with name "video_output" in that folder you can see video files.









Read more ...