Friday, 10 October 2014

Selecting a date from Datepicker using Selenium WebDriver

Calendars look pretty and of course they are fancy too.So now a days most of the websites are using advancedjQuery Datepickers instead of displaying individual dropdowns for month,day,year. :P
If we look at the Datepicker, it is just a like a table with set of rows and columns.To select a date ,we just have to navigate to the cell where our desired date is present.

Step 1:  Here I am taking Sample Website "http://www.cleartrip.com/"
step 2:  Here we can able to select date whatever we want( This is pure dynamic)
step 3:  Here I am Implementing all my logic in 'genericDatePicker()' Method. This method i am   passing date(date format should be dd/mm/yyyy).
step 4: Here First I am Clicking Calendar field and then i am getting Month/Year.
Step 5: I have written Enum method(I am assigning Number to every Month)
Step 6: After that I am calculating total months.
Step 7: Finally I am Clicking the Date From DatePicker..

Here is a sample code on how to pick a 26/10/2016..

  1. package com.utility;

    import java.util.List;

    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.firefox.FirefoxDriver; 
  2. public class RedBus {
      WebDriver driver;
    @Before
    public void setUp() throws Exception {
    driver = new FirefoxDriver();
    driver.get("http://www.cleartrip.com/");
    driver.manage().window().maximize();
    }

    @Test
    public  void datePicker(){
    genericDatePicker("26/09/2016");  //date format should be dd/mm/yy
    }

    public  void genericDatePicker(String inputDate){
    /* CLicking the Date Feild*/
    WebElement ele =driver.findElement(By.id("DepartDate"));  
    ele.click();
    /*Here we are getting Month and Year */
    String month = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[1]")).getText();
    String year = driver.findElement(By.xpath("//div[@class='monthBlock first']/div[1]//span[2]")).getText();
    System.out.println("Application month : "+month + " Year :"+year);
    int monthNum = getMonthNum(month);
    System.out.println("Enum Num : "+monthNum);
    String[] parts = inputDate.split("/");   // Here I am Spliting Our Input String Value
    //Here I am Implementing the Logic
    int noOfHits = ((Integer.parseInt(parts[2])-Integer.parseInt(year))*12)+(Integer.parseInt(parts[1])-monthNum);
    System.out.println("No OF Hits "+noOfHits);
    for(int i=0; i< noOfHits;i++){
    driver.findElement(By.className("nextMonth ")).click();
    }
    /* selecting the month div*/
    List<WebElement> cals=driver.findElements(By.xpath("//div[@class='monthBlock first']//tr"));
    System.out.println(cals.size());
    /*iterating the "tr" list*/
    for( WebElement daterow : cals){
    /*getting the all "td" s*/
    List<WebElement> datenums = daterow.findElements(By.xpath("//td"));
    /*iterating the "td" list*/
    for(WebElement date : datenums ){
    /* Checking The our input Date(if it match go inside and click*/
    if(date.getText().equalsIgnoreCase(parts[0])){
    date.click();
    break;
    }
    }
    }
    }

    // This method will return Month Number
    public  int getMonthNum(String month){
    for (Month mName : Month.values()) {
    if(mName.name().equalsIgnoreCase(month))
    return mName.value;
    }
    return -1;
    }

    // Here I am Creating Enum Method(I am assigning Number to every Month)
    public enum Month {
    January(1), February(2), March(3), April(4), May(5), June(6) , July(7), August(8), September(9), October(10), November(11),December(12);
    private int value;

    private Month(int value) {
    this.value = value;
    }

    }

      @After
    public void tearDown() throws Exception {
    driver.quit();
    }


    }

Wednesday, 8 October 2014

Handling dynamically generated ids in selenium webdriver

Step 1: Here I am trying to automate testing of a webpage that contains list of items. User input item is selected and is deleted. Here, I need to select BR2 and delete that item.

<div id="virtual_domains-content">
    <div class="columns">
        <div class="left-column">
            <h2>Virtual Domains</h2>
                <div class="search-row">
                    <div class="box scrolling list-editable">
                        <div id="virtual_domains-list" class="list-view">
                            <div id="virtual_domains-list-11" class="list-item-view">
                                <div class="content"> BR1</div>
                            </div>
                            <div id="virtual_domains-list-35" class="list-item-view">
                                <div class="content"> BR2</div>
                            </div>
                        </div>
                    </div>

Step 2:In the above code  contains class name.So,I am using  class name.

List<WebElement> list =driver.find_element_by_class_name("list-item-view");
for(WebElement option : list){
    System.out.println(option.getText());
    if(option.getText().equals("BR2")) {
        option.click();
        break;
    }

}

Wednesday, 24 September 2014

As a QA Analyst or software tester, how are you held accountable for the work you are doing?

We developed a checklist. 

1. Do you have Business Requirements documentation? 
2. Has there been a Business Requirements walk through? 
3. Have requirements been signed off? 
4. Is there a Functional Design Document? 
5. Has there been a Functional Design Review 
6. Do you have test plan? 
7. Have you had a test plan review? 
With peers? 
With developers? 
With Business Group? 
8. Has the code been reviewed? 
9. Have smoke tests been completed to accept code into test? (Entrance criteria) 
10. Is testing complete? 
11. Are there open defects? 
12. Do you meet the exit criteria? 
13. Have you had a results verification review? 
Who performed the review 
14. Was the timeline met? 
If no, specify reasons and state action plan 
15. Is the Deployment Plan ready? (MOP) 
16. Is the Deployment Validation Plan ready? 
17. Has the Deployment been completed? 
18. Was the Deployment successful? 
19. Have you archived project documentation?

Friday, 19 September 2014

High level Test process for a company with no formal processes.

My high level test process would include the following: 

1. Inquire - what should you test - ie access the requirements, product, design, etc. 
2. Intent - what will you test and how will you test it, plan your testing 
3. Implement - develop and execute your testing 
4. Inform - analyze, access, and inform others of your test results and recommendations 
5. Iterate - perform steps 1 - 4 as often as is appropriate and feasible given the SDLC 
6. Integrate - perform steps 1 - 5 within the context of the SDLC 
7. "Review - make sure you're doing the right things and doing them the right way by frequently (constantly?) 
8. Inspire - inspire others to embrace quality practices into their roles (as you do in yours) 
9. Integrity - ensure that you perform your tasks and role with professionalism and courtesy

Monday, 4 August 2014

Connecting to DataBase using Selenium WebDriver


Web Driver cannot directly connect to Database. You can only interact with your Browser using Web Driver. For this we use JDBC("Java Database Connectivity").The JDBC API is a Java API for accessing virtually any kind of tabular data.The value of the JDBC API is that an application can access virtually any data source and run on any platform with a Java Virtual Machine.In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do Five things:

1.Load Jdbc driver
Class.forName("com.mysql.jdbc.Driver");

2.Establish a connection with a data source
Connection con =DriverManager.getConnection(dbUrl, userName, password);

3.create Statement Object
Statement stmt = con.createStatement();

4.Send queries and update statements to the data source
ResultSet rs = stmt.executeQuery(query);

5.Process the results
while(rs.next()){

String uName = rs.getString(1);
}

Example Program:

package com.dbconectin;
mport java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class dbConnection {

@Test
public void test() throws ClassNotFoundException, SQLException 
{
try{
//Connection Url
String dbUrl = "jdbc:mysql://localhost:3306/companydb_manf";
//Give Username
String userName ="root";
//Give Password
String password ="root";
//Give Db query
String query = "select * from sr_agritech_estimation_labor where user_id='manager';";

//Load mysql JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Get connection to Db
Connection con =DriverManager.getConnection(dbUrl, userName, password);
//Create Statement Object
Statement stmt = con.createStatement();

//Send Sql query to Db

ResultSet rs = stmt.executeQuery(query);

//While loop to get all data
while(rs.next()){
String uName = rs.getString(1);
String uName1 = rs.getString(2);
String uName2 = rs.getString(3);
String uName3 = rs.getString(4);
String uName4 = rs.getString(5);
System.out.println(uName);
System.out.println(uName1);
System.out.println(uName2);
System.out.println(uName3);
System.out.println(uName4);
System.out.println("-----------------------");
}
//close db connection
con.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

}


}

I guess every one can understand.....;)

Tuesday, 1 July 2014

How To Create And Run JUnit Test Suit For WebDriver Test - Step By Step

If you are planning to perform regression testing of any application using webdriver then obviously there will be multiple test cases or test classes under your webdriver project. Example - There are 2 junit test cases under your project's package. Now if you wants to run both of them then how will you do it? Simple and 
easy solution is creating JUnit test suite. If your project has more than 2 test cases then you can create test suite for all those test cases to run all test cases from one place.
Step 1 - Create new project and package
Create new project in eclipse with name = junitproject and then add new package =
   com.practice.testsuite under your project. 
Step 2 - Create 1st Test Case
Now create JUnit test case under com.practice.testsuite package with class name =
   Junit1 as bellow.
package com.practice.testsuite;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class junittest1 { WebDriver driver = new FirefoxDriver();
public class Junit1 {
 WebDriver driver;
  @Test
  public void f() {
  driver = new FirefoxDriver(); 
  driver.get("https://www.facebook.com/");
  driver.manage().window().maximize();
  driver.quit();
  }
}
Step 3 - Create 2nd test case
Same way, Create 2nd test class with name = Junit2 under package = junitpack as bellow.
package com.practice.testsuite;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class junittest1 { WebDriver driver = new FirefoxDriver();
public class Junit2 {
 WebDriver driver;
   @Test
  public void f() {
    driver = new FirefoxDriver(); 
   driver.get("https://www.google.com/");
   driver.manage().window().maximize();
   driver.quit();
  }
  @Test
  public void f() {
  driver = new FirefoxDriver(); 
  driver.get("https://www.facebook.com/");
  driver.manage().window().maximize();
  driver.quit();
  }
}

Step 4 - Create test suite for both test cases
Now we have 2 test cases(Junit1.java and jJunit2.java) under package = com.practice.testsuite.
To create test suite, Right click on com.practice.testsuite package folder and Go to -> New -> Other -> Java -> Junit ->  Select 'JUnit Test Suite'
package com.practice.testsuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses

@RunWith(Suite.class)
@SuiteClasses({Junit1.class,Junit2.class})
public class JunitSuite {

}

Step 5- Running test suite
 When you run JunitSuite test suite, eclipse will run both test cases (Junit1 and Junit2) one by one. When execution completed, you will see  output lines in console.



Tuesday, 27 May 2014

WebDriver: check if an element exists or not?

IF you are a Selenium Web Driver  Automation tester than most probably you would have gone through this situation, In which you have faced one exception that speaks “Element not found”.

I Found Solution for this scenario........

Case 1:
 boolean elements ;
  elements = driver.findElements(By.name("masterPassword")).isEmpty();
  if(elements == true)
  {
     System.out.println("Element is not present");  
  }
  else
  {
           System.out.println("Element is present");  
          //Do whatever You want
  }

Here i am checking whether the element is present or not. Based on that I am writing if() {}and else{} blocks.

Wednesday, 5 March 2014

Error:Unable to bind to locking port 7054 within 45000 ms

org.openqa.selenium.WebDriverException: Unable to bind to locking port 7054 within 45000 ms 
Build info: version: '2.30.0', revision: 'dc1ef9c', time: '2013-02-19 00:15:27' 
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0' 
Driver info: driver.version: FirefoxDriver 
Command duration or timeout: 47.94 seconds 
Build info: version: '2.28.0', revision: '18309', time: '2012-12-11 15:53:30' 
System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.7.0' 
Driver info: org.openqa.selenium.remote.RemoteWebDriver

Solution1: This generally means you have another copy of Firefox running on that
system. 
Solution2 : Try Uninstalling FireFox completely and then Install Firefox .

Monday, 24 February 2014

How To Close Popup Window in Selenium Webdriver


This Method will Solve Your Problem:


private void  handleWindow() {
 try {
      String parent = driver.getWindowHandle();

      Set<String> pops=driver.getWindowHandles();
       {
 Iterator<String> it =pops.iterator();
while (it.hasNext()) {

 String popupHandle=it.next().toString();
 if(!popupHandle.contains(parent))
{
                   driver.switchTo().window(popupHandle);
 System.out.println("Popu Up Title: "+ driver.switchTo().window(popupHandle).getTitle());
 driver.close();
  driver.switchTo().window(parent);  // control is moving to parent window
        }
       }
}
} catch (NoAlertPresentException e) {
         e.printStackTrace();
 }

}

Thursday, 20 February 2014

WebDriver’s most popular Commands


Selenium WebDriver is like a magic wand to automation tester to test the web application. Selenium WebDriver has not only  made automation more Object oriented through it OOPs API  but it has also solve the  the most complaining performance of browser launching in Selenium 1.0 and the most important thing that has given a panacea to automation engineers’ hand is its ability to Single Host origin policy.
Selenium WebDriver has left more impact on functional test coverage, like the file upload or download, pop-ups and dialog’s barrier
Today I am going to post most common functions used in Selenium WebDriver to make a journey of automation testing through WebDriver
  1. IsElementPresent/Text Present  function in Selenium WebDriver
    1. Finding elements by using function that take argument of By classprivate boolean isElementPresent(WebDriver driver, By by)
      try{
      driver.findElement(by);
      return true;
      }
      catch(Exception e)
      {
      return false;
      }
      }
    2. Using the size to decide whether element is there or not
      if(driver.findElements(Locator).size()>0
      {
      return true
      }else
      {
      return false
      }
      }
    3. Finding the text using the PageSourcedriver.PageSource.Contains("TEXT that you want to see on the page");
  2. Finding WebElement  by using various locators in WebDriver
    1. Using ID  WebElement welement = driver.findElement(By.id("Id from webpage"));
    2. Using Name  WebElement welement = driver.findElement(By.name("Name of WebElement"));
    3. Using Tag Name  WebElement welement = driver.findElement(By.tagName("tag name"));
    4. Using Xpath  WebElement welement = driver.findElement(By.xpath("xpath of  webElement"));
    5. Using CSS  WebElement welement = driver.findElement(By.CSS("CSS locator path"));
    6. Using LinkText  WebElement welement = driver.findElement(By.LinkText("LinkText"));
  3. Fetching pop-up message in Selenium-WebDriver
    this is the function that would help you in fetching the message

    public static String getPopupMessage(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.accept();
    } catch (Exception e) {
    message = null;
    }
    System.out.println("message"+message);
    return message;
    }
  4. Canceling pop-up in Selenium-WebDriver
    public static String cancelPopupMessageBox(final WebDriver driver) {
    String message = null;
    try {
    Alert alert = driver.switchTo().alert();
    message = alert.getText();
    alert.dismiss();
    } catch (Exception e) {
    message = null;
    }
    return message;
    }
  5. Inserting string in Text Field in Selenium-WebDriverpublic static void insertText(WebDriver driver, By locator, String value) {
    WebElement field = driver.findElement(locator);
    field.clear();
    field.sendKeys(value);
    }
  6. Reading ToolTip text in in Selenium-WebDriver
    public static String tooltipText(WebDriver driver, By locator){
    String tooltip = driver.findElement(locator).getAttribute("title");
    return tooltip;
    }
  7. Selecting Radio Button in Selenium-WebDriver
    public static void selectRadioButton(WebDriver driver, By locator, String value){ List select = driver.findElements(locator);
    for (WebElement element : select)
    {
    if (element.getAttribute("value").equalsIgnoreCase(value)){
    element.click();
    }
    }
  8.  Selecting CheckBox in Selenium-WebDriver

    public static void selectCheckboxes(WebDriver driver, By locator,String value)
    {
    List abc = driver.findElements(locator);
    List list = new ArrayListArrays.asList(value.split(",")));
    for (String check : list){
    for (WebElement chk : abc){
    if(chk.getAttribute("value").equalsIgnoreCase(check)){
    chk.click();
    }}}}
  9. Selecting Dropdown in Selenium-WebDriverpublic static void selectDropdown(WebDriver driver, By locator, String value){
    new Select (driver.findElement(locator)).selectByVisibleText(value); }
  10. Selecting searched dropdown in Selenium-WebDriverpublic static void selectSearchDropdown(WebDriver driver, By locator, String value){
    driver.findElement(locator).click();
    driver.findElement(locator).sendKeys(value);
    driver.findElement(locator).sendKeys(Keys.TAB);
    }
  11. Uploading file using  Selenium-WebDriverpublic static void uploadFile(WebDriver driver, By locator, String path){
    driver.findElement(locator).sendKeys(path);
    }
  12. Downloading file in Selenium-WebDriverHere we will click on a link and will download the file with a predefined name at some specified location.
    public static void downloadFile(String href, String fileName) throws Exception{
    URL url = null;
    URLConnection con = null;
    int i;
    url = new URL(href);
    con = url.openConnection();
    // Here we are specifying the location where we really want to save the file.
    File file = new File(".//OutputData//" + fileName);
    BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
    BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file));
    while ((i = bis.read()) != -1) {
    bos.write(i);
    }
    bos.flush();
    bis.close();
    }
  13. Handling multiple Pop ups 
    read  Handling Multiple Windows in WebDriver
  14. Wait() in Selenium-WebDriver
    1. Implicit Wait :
      driver.manage.timeouts().implicitlyWait(10,TimeUnit.SECONDS);
    2. Explicit Wait:WebDriverWait wait = new WebDriverWait(driver,10);
      wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/name("locator"));
    3.  Using Sleep method of java
      Thread.sleep(time in milisecond)
  15. Navigation method of WebDriver Interface
    1. to() method (its a alternative of get() method)
      driver.navigate().to(Url);
      This will open the URL that you have inserted as argument
    2. back() – use to navigate one step back from current position in recent history syntax == driver.navigate().back();
    3. forward() – use to navigate one step forward in browser historydriver.navigate().forward();
    4. refresh() – This will refresh you current open urldriver.navigate().refresh();
  16. Deleting all Cookies before doing any kind of action  driver.manage().deleteAllCookies();
    This will delete all cookies
  17. Pressing any Keyboard key using Action builder class of WebDriverWebDriver has rewarded us with one class Action to handle all keyboard and Mouse action. While creating a action builder its constructor takes WebDriver as argument. Here I am taking example of pressing Control key
    Actions builder = new Actions(driver);
    builder.keyDown(Keys.CONTROL).click(someElement).click(someOtherElement).keyUp(Keys.CONTROL).build().perform();
    When we press multiple keys or action together then we need to bind all in a single command by using build() method and perform() method intend us to perform the action.
    In the same way you can handle other key actions.
  18. Drag and Drop action in Webdriver
    In this we need to specify both WebElement  like Source and target and for draganddrop Action class has a method with two argument so let see how it normally look like
    WebElement element = driver.findElement(By.name("source"));
    WebElement target = driver.findElement(By.name("target"));
    (new Actions(driver)).dragAndDrop(element, target).perform();

Angular JS Protractor Installation process - Tutorial Part 1

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