Wednesday, February 17, 2016

Actions to automate SVG HighCharts

In previous post we have seen what are Actions, in this section using Actions will automate SVG HighCharts. 

Below script will open chrome browser and navigate to http://www.highcharts.com/demo/bar-basic
and then mouse move to particular data point element and display the tooltip information. 


Script :



output on the console

Africa




Tuesday, February 16, 2016

How to handle Java Scripts Alerts in Webdriver

In general JavaScript popups are generated by web application and can be handled by WebDriver.
Webdriver offers the ability to handle with javascript alerts using Alerts API
// Get a handle to the open alert, prompt or confirmation
 Alert alert = driver.switchTo().alert();
//Will Click on OK button.
alert.accept(); 
alert.authenticateUsing(Credentials credentials)


// Will click on Cancel button.
alert.dismiss()
//will get the text which is present on the alert.
alert.getText(); 
//Will pass the text to the prompt popup

alert.sendkeys();
Alert is an interface. There below are the methods that are used
 Lets take an example 
1. Open google chrome 
2. Navigate to site : http://admin-demo.nopcommerce.com/login
3. Go to Catalog->Product tags
4. And delete the product

SCRIPT :


Listeners and EventFiringWebDriver in Selenium Webdriver


Before getting in we should talk about webdriverEvent listeners and EvebtFiringWebDriver interfaces.
1- WebDriverEventListener – This is an interface, which have some predefined methods so we will implement all of these methods.
2-EventFiringWebDriver- This is an class that actually fire Webdriver event.
Why we are using Webdriver Listeners
How to implement Listener in our Script
Step 1- Create a new Class that will implement WebDriverEventListener methods
In general for every action that runs we need to perform some activity logging ex. click, navigate etc and these are called events. So when ever we run script these actions logging will happen through these listeners and track them .
Take an example if you perform click then what should happen before click and after click.
To capture these events we will add listener that will perform this task for us.
Program for what is listeners in selenium webdriver
and call this as ActivityCapture



for more details about webDriver listener click here : 



In above method we are just printing on console and this method will automatically called once click events fired.   
Step 2- Now create your simple script, create EventFiringWebDriver object, and pass your driver object.
EventFiringWebDriver myevent=new EventFiringWebDriver(driver);
Step 3- Create an object of the class who has implemented all the method of WebDriverEventListener so in our case ActivityCapture is a class who has implemented the same.
ActivityCapture handler=new ActivityCapture();
Step 4- Now register that event using register method and pass the object of ActivityCapture class
myevent.register(handler);
 Implementation of Webdriver listener
Now create a main java class as ListenersAndEventFiring 
In below sample scripts it will try to log in twitter account and for each actions the WebDriverEventListener and print on the screen. 


Sample console output :

Started Webdriver listener demo...

Before navigating https://twitter.com/login
Before navigating FirefoxDriver: firefox on MAC (ec52d8fa-3c3c-5140-a30e-3daf2dc4536f)
After navigating https://twitter.com/login
After navigating FirefoxDriver: firefox on MAC (ec52d8fa-3c3c-5140-a30e-3daf2dc4536f)
before FindBY By.xpath: //*[@id='page-container']/div/div[1]/form/fieldset/div[1]/input
After FindBy By.xpath: //*[@id='page-container']/div/div[1]/form/fieldset/div[1]/input
before FindBY By.xpath: //*[@id='page-container']/div/div[1]/form/fieldset/div[2]/input
After FindBy By.xpath: //*[@id='page-container']/div/div[1]/form/fieldset/div[2]/input
before FindBY By.xpath: //*[@id='page-container']/div/div[1]/form/div[2]/button
After FindBy By.xpath: //*[@id='page-container']/div/div[1]/form/div[2]/button
before click [[FirefoxDriver: firefox on MAC (ec52d8fa-3c3c-5140-a30e-3daf2dc4536f)] -> xpath: //*[@id='page-container']/div/div[1]/form/div[2]/button]
After click [[FirefoxDriver: firefox on MAC (ec52d8fa-3c3c-5140-a30e-3daf2dc4536f)] -> xpath: //*[@id='page-container']/div/div[1]/form/div[2]/button]
End of listener demo....




Implicit/Explicit / Fluent Waits




WebDriver supports two waits in order to handle the synchronisation problems.
  • Implicit Wait
  • Explicit Wait
Let us discuss each of them in details considering practical approach.

WebDriver Implicit Wait

Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script. Thus, subsequent test step would only execute when the 30 seconds have elapsed after executing the previous test step/command.
Syntax : Syntax
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
The above snippet code will take two parameters, the first indicates the tie in numeric that system need to wait and the second parameter indicates the time measurement. so in this case it will wait for 10 seconds, and Once set, the implicit wait is set for the life of the WebDriver object instance.

Ex. 

WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://timetracker.anuko.com/login.php"); WebElement loginelement = driver.findElement(By.id("login"));


When to use: Not recommended

WebDriver explicit waits

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://timetracker.anuko.com/login.php");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
  .until(ExpectedConditions.visibilityOf(By.id("login")));

Please refer this docs for more details for other method options. 

Will see live implementation :
1. Launch google chrome 
2. open time tracker login page
3. before enter the username data check whether element is present or not and then enter the value
4. Also will create a common method to wait for element present



Fluent wait :


For each FluentWait instance, you can specify:
  1. Frequency with which FluentWait has to check the conditions defined.
  2. Ignore specific types of exception waiting such as NoSuchElementExceptions while searching for an element on the page.
  3. Maximum amount of time to wait for a condition
When to use FluentWait: When you try to test the presence of an element that may appear after every x seconds/minutes (Just an example, this is my guess of where such a thing can be used).

Ex :



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

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



Example that covers fluent waits 





Browser Developer tools and Add-ons



To automate with selenium first we need get the locators understanding (In previous post we have seen the locator strategy), in this post we focus on tools that helps us in getting right locator to automate. 


Will focus on below objective 


Developer Tools is a web application that is written in HTML, JavaScript and CSS. The application is triggered at JavaScript runtime. Once triggered, it allows us to interact with web pages and play around with them. 


Opening the Developer Tools in various browsers
Internet Explorer
To open the Developer Tools in Internet Explorer, press F12; alternatively, on the Tools menu of the Internet Explorer, click Developer Tools.
Once initiated, the Developer Tools can be on their own window or pinned to the browser's instance that opened it. Each Internet Explorer tab has its own instance of the Developer Tools. When working with multiple instances of the Developer Tools, use the Pin feature whose button appears in the upper-right corner of the Developer Tools window. This attaches each Developer Tools to its window. When pinned, the Developer Tools window can be resized to display a larger viewable area. 

  •   Select the Menu at the top-right of your browser window, then select Tools > Developer Tools.
  •   Right-click on any page element and select Inspect Element.
  •  Firefox
  •  Developer Tools can be opened in either one of the ways described below:
  •   Press Shift+F2.
  •   Go to the Web Developer menu (which is a submenu in the Tools menu on Mac OS X and Linux) and choose "Developer Toolbar".
  •  
Understand Firebug and Xpath Checker add-ons
Understand basics of browser Developer Tools 
Describe the Chrome Developer Tools

Developer Tools  - Each browser comes with option of Developer tools this will help us in locating the element of give web page. 

Every modern web browser includes a powerful suite of developer tools. 
These tools perform a range of things, from inspecting the currently-loaded HTML, CSS (Cascading Style Sheets) and JavaScript to showing which assets the page has requested and how long they took to load.

Google Chrome
Developer Tools can be opened in either one of the ways described below:
  • Firebug Add-on

    Firebug is a free and open source popular Add-on tool distributed under the BSD License which integrates with Firefox browser. It allows to debug and inspect HTML, CSS, the Document Object Model (DOM) and JavaScript live in any web page.

    Install Fire Bug
    Go to this URL https://addons.mozilla.org/en-US/firefox/addon/firebug/


    Click on Add to Firefox button and install the plugin and restart firefox if needed.



    Launch Fire bug


    With the Mozilla Firefox browser open:

    •   Press F12 on the keyboard or
    •   Press the Firebug button on the toolbar or right click and launch fire bug as shown below



      How to inspect element with fire bug
      Launch site : https://timetracker.anuko.com/login.php
      right click and click on "insect element with fire bug"






      Please watch video for detailed steps :





    WebDriver Element Locator Plugin
    Go to this URL and add the plugin to Firefox (make sure you open the plugin in firefox browser)


    https://addons.mozilla.org/en-US/firefox/addon/element-locator-for-webdriv/




    Now locate an element with WebDriver Element  Locator plugin

    Go to any site right click and navigate to WebElement Locator and start analysing the xpath. In this case navigate to https://timetracker.anuko.com/login.php








Must know about LOCATORS

Must know about Locators 

Selenium uses what is called locators to find and match the elements of your page that 
it needs to interact with. There are 7 locators strategies included in Selenium:

Link

XPath (cheat sheet for XPATH)
ID
Name
CSS
UI-element 
DOM

Example html source code.



<html>
  <body>
    <form id="login">
      <input name="username" type="text"/>
      <input name="password" type="password"/>
<input name="submit" type="submit" value="Continue!"/>
    </form>
  </body>
</html>


  •  Easily matches several elements: try to name your username field as login
  • Note
  • Usually, you don’t need to specify the locator prefix, Selenium will be able to infer the locator type by itself

1.1. Identifier
works with the id and name attributes of your html tags. Let’s consider the following example: 


Valid locators for this snippet are :
identifier=username
identifier=login
submit

PROS:

This strategy doesn’t rely on the structure of the page and will work even if it changes.
CONS:
  • 1.2 The Id strategy looks for an element in the page having an id attribute corresponding
    to the specified pattern. <label id="my_id" /> will be matched by a locator like id=my_id or just my_id
    Pros :
       Each id is supposed to be unique so no chance of matching several elements
    CONS : Works well only on elements with fixed ids and not generated ones
    <html>
    <body>
      <div id="pancakes">
        <button type="button" name="pancake" value="Blueberry">Blueberry</button>
        <button type="button" name="pancake" value="Banana">Banana</button>
        <button type="button" name="pancake" value="Strawberry">Strawberry</button>
    
      </div>
    </body>
    

    Works well with fixed list of similar elements

    1.3 NAME
    Like the Id strategy, but on the name attribute. You can also specify a filter to refine your locator. Currently, there are two filter types :
    Value : matches elements with a name attribute and where the value follows a pattern. The following example illustrates the interest of filters :

    Scenario:
    we just added a strawberry pancake in our application and we want to test that the button that adds it into the cart works. With a locator like name=pancake, Selenium will find 3 elements and return the first one : the test will never fail even if the strawberry button is not here! Use a value filter like name=pancake value=Strawberry and the locator successfully identifies the Strawberry button.
    Index : same as name but works with an index. Using the previous example, the locatorname=pancake index=2 will select the Strawberry button.

    Tip
    the index starts at 0


    PROS:
    CONS:
    Difficult to use with data-bound lists 

    1.4 
    LINK
    This strategy is intended to select links only and selects the anchor element containing the specified text: link=The text of the link
    PROS:

    You have to know the text of the link before 

    •  Will only select anchor elements
    •  Useful when testing navigation

    CONS:

    1.5 DOM
    The DOM strategy works by locating elements that matches the javascript expression referring to an element in the DOM of the page.
    document.div[0].button[2]dom=function foo() {
    xpath=//button[@value="Blueberry"]: matches the Blueberry button
    //div[@id="pancakes"]/button[0]: same thing

    Allows very precise locators
    Name
    Link

dom=document.div['pancakes'].button[0]

PROS : 



Javascript allows you to build dynamic locators
CONS :

Relies on the structure of the page


1.6 XPATH



While DOM is the recognized standard for navigation through an HTML element tree, XPath is the standard navigation tool for XML; and an HTML document is also an XML document (xHTML). XPath is used everywhere where there is XML. Valid XPath locators can be:
PROS:
CONS:
  •  Slower than CSS
  •  Relies on browser’s XPath implementation which is not always complete (especially
    on IE) and as such is not recommended for cross-browser testing 

CSS :
In WebDriver, in order to interact with a web element, such as clicking, or typing, we first need to locate the elements. In previous tutorial, we discussed the different ways we can locate the web elements.
In this WebDriver tutorial, we look at how we can use CSS Selectors in more detail and with examples to interact with web elements.
Using CSS selectors to locate elements has some benefits:
1. It’s faster;
2. It’s more readable;
3. It’s more used.
Locating Elements by Attribute
Let’s imagine we have a tag with the following attributes [id, class, name, value]

The generic way of locating elements by their attribute in CSS Selectors is

e.g.

We can use the same approach to lo
cate by id and class attributes, however, there are short forms that we can use to make it more readable.

In CSS, we can use # notation to select the id:
e.g.


We can also use the . notation to select the class


Take extra care when using the short form notations, especially the . class notation as there could be many web elements on the html source with the same class attribute.

Locating elements by More Than One Attribute
Sometimes there is a need to be more specific with the selection criteria in order to locate the correct element.
Suppose you have a html snippet as below

The value of the display could either be “none” or “block” depending on the ajax call. In this situation we have to locate the element by both class and style.

We could use

Locating Child Element

To locate the image tag, we would use:

There are occasions when there are multiple child elements within the same parent element such as list elements

As can be seen, the individual list elements don’t have any id associated with them. If we want to locate the element with text ‘Orange’, we have to use “nth-of-type”


Similarly, if we need to select the last child element, i.e. ‘Banana’, we can use

Strings and Randomly Generated Ids
We can also use string matchers to locate elements:

To select the first div element, we would use ^= which means ‘starts with’:

To select second div element, we would use $= which means ‘ends with’:

To select the last div element we would use *= which means ‘sub-string’



We can also use the ‘contains’

Structure 



Structure-Dependent Or Not?
Locators can be classified into two categories:
  •  UI-element is a rather new locator
  •  It was at first a Selenium IDE extension
  •  It is now fully integrated into Selenium
  •  See the Section 9.4, “UI-Elements:”

o Structure-based locators: locators that rely on the structure of the page to find elements.

XPath DOM

o Attributes-based locators: locators that relies on the attributes of the elements to locate them

Identifier Id
CSS
  •  You should consider this before choosing a locator strategy
  •  Most people choose CSS because it is the most flexible and gives a good balance
    between using structure and attributes to find the elements 

  

Working with Date Picker


Go to site : expedia.co.in and try to pick the dates

Script :


Output :




Actions Class -- Drag and Drop

Go to site :
http://demos.telerik.com/aspnet-ajax/listbox/examples/functionality/draganddrop/defaultcs.aspx
Drag and drop the components (means drag location Brazil and drop to other component.


Actions Class -- how to navigate to menu items

We have seen in previous post about actions

Go to site : amazon.in
and move to particular element using action class

More info : http://selenium.googlecode.com/svn@7074/trunk/docs/api/java/index.html



Actions Class - how to simulate keyboard actions

In Webdriver, handling keyboard events and mouse events (including actions such as Drag and Drop or clicking multiple elements With Control key etc...) are done using the advanced user interactions API . It contains Actions and Action classes which are needed when performing these events.
In order to perform action events, we need to use org.openqa.selenium.interactions.Actions class.
sample :
// Configure the Action Actions myaction = new Actions(driver); // To click on the element myaction.moveToElement(element).click().perform();
Go to Site : www.flipcart.com and search for iPhone and press down arrow two times and then hit enter.