Showing posts with label Selenium RC. Show all posts
Showing posts with label Selenium RC. Show all posts

Friday, July 1, 2011

Selenium RC using Page Objects.

Within your web app's UI there are areas that your tests interact with. A Page Object simply models these as objects within the test code. This reduces the amount of duplicated code and means that if the UI changes, the fix need only be applied in one place. 

 Example for Page Object:
Homepage.java

package com.sai.pageobjects;

import com.thoughtworks.selenium.Selenium;

public class HomePage {

    private Selenium selenium;

    public HomePage(Selenium selenium) {
            if (!selenium.getText("//div[2]/div[2]/div[2]/div/div").equals("Now you can use Gmail in more languages!   Learn more")) {
                    throw new IllegalStateException("This is not Home Page of logged in user, current page" +
                                    "is: " +selenium.getLocation());
            }
    }

    public HomePage manageProfile() {
            // Page encapsulation to manage profile functionality
            return new HomePage(selenium);
    }
}

SignInPage.java

package com.sai.pageobjects;

import com.thoughtworks.selenium.Selenium;

public class SignInPage {

    private Selenium selenium;

 
    public SignInPage(Selenium selenium) {
            this.selenium = selenium;
            if(!selenium.getTitle().equals("Gmail: Email from Google")) {
                    throw new IllegalStateException("This is not sign in page, current page is: "
                                    +selenium.getLocation());
            }
    }

    /**
     * Login as valid user
     *
     * @param userName
     * @param password
     * @return HomePage object
     */
    public HomePage loginValidUser(String userName, String password) {
       
            selenium.type("Email", userName);
            selenium.type("Passwd", password);
            selenium.click("signIn");
            selenium.waitForPageToLoad("30000");

            return null ;
    }
}

testLogin.java

package com.sai.pageobjects;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.server.SeleniumServer;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestCase;


@SuppressWarnings("deprecation")
public class TestLogin extends SeleneseTestCase{
    @Before
    public void setUp() throws Exception {
        selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com/");
        SeleniumServer seleniumServer = new SeleniumServer();
         seleniumServer.boot();
        selenium.start();
        selenium.windowFocus();
        selenium.windowMaximize();
    }
@Test
    public void testLogin() throws Throwable {
    selenium.open("/");
    selenium.click("//li[7]/a/span[2]");
    Thread.sleep(10000);
            SignInPage signInPage = new SignInPage(selenium);
            HomePage homePage = signInPage.loginValidUser("username", "password");
            Assert.assertEquals(selenium.isElementPresent("compose button"),
                            "Login was unsuccessful");
    }
}

Get attribute for an element

Using xPath: 
 
String var = selenium.getAttribute("//input[@name='q']/@maxlength");
        System.out.println(var);
 
Using csslocator:
String var = selenium.getAttribute("css=input[name='q']@maxlength");
        System.out.println(var);
 
Using webdriver: 
String var = webDriver.findElement(By.xpath("//input[@name='q']")).getAttribute("maxlength")
        System.out.println(var);  

Friday, June 10, 2011

How to Automate Pacman with Selenium 2

import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class WebDriverScratchPad {
 
 public static final long PAUSE = 2000;
 
 public static final Keys UP = Keys.ARROW_UP;
 public static final Keys DOWN = Keys.ARROW_DOWN;
 public static final Keys LEFT = Keys.ARROW_LEFT;
 public static final Keys RIGHT = Keys.ARROW_RIGHT;
 
 public static WebElement controls;
 
 public static void main(String [ ] args) throws InterruptedException {
  WebDriver driver = new FirefoxDriver();
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
  driver.get("http://www.google.com/pacman/");
  controls = driver.findElement(By.id("pcm-c"));
 
  move(LEFT, UP, LEFT, DOWN, LEFT, UP, LEFT, DOWN, RIGHT);
 }
 
 private static void move(Keys... directions) {
  for (Keys direction : directions) {
   controls.sendKeys(direction);
   try {
    Thread.sleep(PAUSE);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
}

Friday, January 21, 2011

How to write results to excel sheet

After successfully executing scripts, every one want to write results to excel sheet..here is the way to write results to excel sheet....




package test;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import com.thoughtworks.selenium.*;

import org.openqa.selenium.server.*;
import org.testng.annotations.*;

public class Importexport1 {
public Selenium selenium;
public SeleniumServer seleniumserver;

@BeforeClass
public void setUp() throws Exception {
RemoteControlConfiguration rc = new RemoteControlConfiguration();
seleniumserver = new SeleniumServer(rc);
selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");
seleniumserver.start();
selenium.start();
}

@Test
public void testImportexport1() throws Exception {

// Read data from excel sheet
FileInputStream fi = new FileInputStream(
"F:\\Framework\\testdata\\Login1_Credentials.xls");
Workbook w = Workbook.getWorkbook(fi);
Sheet s = w.getSheet(0);
String a[][] = new String[s.getRows()][s.getColumns()];
// Write the input data into another excel file
FileOutputStream fo = new FileOutputStream(
"F:\\Framework\\Results\\LoginResult1.xls");
WritableWorkbook wwb = Workbook.createWorkbook(fo);
WritableSheet ws = wwb.createSheet("loginresult1", 0);

selenium.open("http://www.gmail.com");
selenium.windowMaximize();

System.out.println("s.getRows() = " + s.getRows());

for (int i = 0; i < s.getRows(); i++) {
System.out.println("s.getColumns = " + s.getColumns());
for (int j = 0; j < s.getColumns(); j++) {
a[i][j] = s.getCell(j, i).getContents();
Label l = new Label(j, i, a[i][j]);
Label l1 = new Label(2, 0, "Result");
ws.addCell(l);
ws.addCell(l1);
}
}

for (int i = 1; i < s.getRows(); i++) {
selenium.type("Email", s.getCell(0, i).getContents());
selenium.type("Passwd", s.getCell(1, i).getContents());
selenium.click("signIn");
selenium.waitForPageToLoad("30000");

boolean aa = selenium.isTextPresent("The username or password you entered is incorrect. [?]");
System.out.println("the value of aa is::" + aa);
if (aa)

{

Label l3 = new Label(2, i, "fail");

ws.addCell(l3);
System.out.println("Login Failure");
Thread.sleep(10000);

} else {

Label l2 = new Label(2, i, "pass");

ws.addCell(l2);
selenium.click("link=Sign out");
Thread.sleep(10000);
}
}
wwb.write();
wwb.close();
}

@AfterClass
public void tearDown() throws Exception {
selenium.stop();
seleniumserver.stop();

}
}

Wednesday, January 19, 2011

Try and Catch method for page to load

for (int second = 0; second < 60; second++) {
            try {

                if (selenium.isElementPresent("//input[@value='Search']"));
                  selenium.click("//input[@value='Search']");
                Condition = true;
                selenium.waitForPageToLoad("20000");
                break;

            } catch (Exception ignore) {
            }
            pause(1000);
        }
        assertTrue(Condition);


Sometimes we get Timed error on waitForPageToLoad command

To over come this error we can ues Try and Catch method .

Running your first selenium test case in eclipse


1- In FireFox ,Start Your Selenium-IDE from tools->Selenium IDE
2- Record your script
3- Go to File->Export test case as->Choose the programing language as JAVA and save your script.
4-Save it with .java extension

The next step is to open your eclipse and create a project.

1- Creating your java project in eclipse
The first step in eclipse is to create/add your project. To do this follow the steps below:
-> Launch Eclipse
-> Right click in navigator->Create a java project named TestProject (for example)

2- The next step is to add JUnit Libraries which consists of following steps:
-> Go to Project Properties
-> Go to Java Build Path
-> Click on Add external-jar button in Libraries tab
-> Browse and go to the location where u stored ur junit.jar.

4-Add Selenium Java Client Jar into Project:-
Once you added the Junit jars , the next step is to add selenium jar file. you can find selenium-server.jar under selenium-remote-control\selenium-java-client-driver folder what you have downloaded from

http://selenium-rc.openqa.org/download.html

To add this Jar file follow the below steps:
-> Go to Project Properties
-> Go to Java Build Path
-> Click on Libraries tab
-> Click on 'Add External Jars' button
-> Browse and add the 'selenium-server.jar' from the source where you had saved it.

5- Initiating the Selenium Test Server
To start the selenium test server, first go to the location where your selenium-server.jar is placed.
and then Run the command java -jar selenium-server.jar

This will start you selenium server.

6- Adding your test (Java class ) in our Project
To add you test (which you have saved earlier) as a java class file to the project (TestProject, already saved) follow the steps:
-> In eclipse go to create a new java class
-> Create it with name MyFirstTestCase (for example) and paste the code from the file u had saved it
-> Choose "com.thoughtworks.selenium.SeleneseTestCase" as its super class
-> Finish it

7- Modifying your test script (java class)
Once you are done with ur class file, it will look like,

Package.*
import com.thoughtworks.selenium.SeleneseTestCase ;
public class MyFirstTestCase extends SeleneseTestCases {
public void setUp() throws Exception {
setUp( " http://www.google.com/ " , "*firefox'); }

............ You test script..............
}

In case you want to run this in diff browser then simply you can change your script
setUp( " http://www.google.com/ " , "*firefox');
to setUp( " http://www.google.com/ " , "*chrome'); or whatever browser you need to run with.

8- Running your test
Finally we are ready to tun our first test. To run this in eclipse you click on Run button
select option Run as "JUnit Test'

So finally I am done with your end to end execution of ur java test case using selenium RC in eclipse. For report generation using JUnit in eclipse.

How to stop the selenium server manually.

At times when your about to run your scripts you get an error saying selenium server already running  in port 4444

to stop the server just paste the below URL in your browser

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

if u get OKOK which states that your server is running just refresh the page and run your scripts .

How to get the values from the Drop Down menu.


package smoke;

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class dropdownvalue {
     public Selenium selenium;
     public SeleniumServer seleniumserver;

       @BeforeClass
       public void setUp() throws Exception {
     RemoteControlConfiguration rc = new RemoteControlConfiguration();
     seleniumserver = new SeleniumServer(rc);
     selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.google.com");
     seleniumserver.start();
     selenium.start();
     }

     @Test
     public void testDefaultTNG()throws Exception {
     selenium.open("http://www.google.com");


     selenium.click("link=Advanced Search");
     selenium.waitForPageToLoad("50000");
     // Print all the available options from the results dropdown in the
     String[] options = selenium.getSelectOptions("name=num");
     // The above command returns a array of strings(options)
     for (int i = 0; i < options.length; i++) {
         System.out.println("Option: " + i + " is " + options[i]);
         }
         //select value from dropdown
             selenium.select("num", "label=30 results");
             //Print the selected value from dropdown
         String s=selenium.getSelectedValue("name=num");
         System.out.println("selected value is "+s);
         
         
     }
     @AfterClass
      public void tearDown() throws InterruptedException{
     selenium.stop();
     seleniumserver.stop();
     
      }
      }

Count the No of Check Box , Check them and print the values of the checkboxes



int checkboxcount=selenium.getXpathCount("//input[@type='checkbox']").intValue();
            System.out.println("The Number of checkbox :" +checkboxcount );

// intValue() function will  get the number the checkbox's in the page .

for (int i = 1; i <= checkboxcount; i++) {
                       if (selenium.isElementPresent("//input[@type='checkbox']"))
                       {
                           selenium.click("xpath=(//input[@type='checkbox'])[position()="+ i + "]");

                         String str= selenium.getText("xpath=(//label[@class='x-form-cb-label'])[position()="+ i + "]");
                 System.out.println("string----"+str );
}

Here checkbox count will be displayed and the count value is taken as checkboxcount into the "for"  loop
and "i" is incremented within the xpath . so that it will print all the values of the checkbox in the page

Locating Elements with the same Name .

If we have a Two Button with the same name as " ABC "

selenium.click("//input[@id='button'and position()=2 ]");

 selenium.click("//input[@id='button'and position()=1 ]");

postion()=1 will click on the first button .
position()=2 will click on the second button.

Data Driven Testing Using Testng

package shakeWeight;

import com.thoughtworks.selenium.*;

import org.junit.AfterClass;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.*;

import java.io.File;
import jxl.*;

public class Yellow extends SeleneseTestCase {
    boolean Condition = true;

    @BeforeClass
    public void setUp() throws Exception {
        SeleniumServer seleniumserver = new SeleniumServer();
        seleniumserver.boot();
        seleniumserver.start();
        setUp("http://test04.yellowbook.com", "*firefox");
        selenium.open("/yellow-pages/?what=lawyers&where=Denver%2C+CO");
        selenium.windowMaximize();
        selenium.windowFocus();
    }

    @DataProvider(name = "DP1")
    public Object[][] createData1() throws Exception {
        Object[][] retObjArr = getTableArray(
                "test\\Resources\\Data\\Book1.xls", "DataPool", "yellowbook");
        return (retObjArr);
    }

    @Test(dataProvider = "DP1")
    public void testDataProviderExample(String what1, String where1,
            String search1) throws Exception {
        // enter the movie title

        selenium.type("what", what1);
        selenium.type("where", where1);
        for (int second = 0; second < 60; second++) {
            try {

                if (selenium.isElementPresent("//input[@value='Search']"))
                    ;
                selenium.click("//input[@value='Search']");
                Condition = true;
                selenium.waitForPageToLoad("20000");
                break;

            } catch (Exception ignore) {
            }
            pause(1000);
        }
        assertTrue(Condition);
        // they keep switching the go button to keep the bots away
        //boolean gold_ad = selenium.isElementPresent("//div[@class=\"adFlag-gold\"]");
        //System.out.println("Searching for the text :: "+search1 +" Is Available :: "+selenium.isTextPresent(search1)+" IS Gold-Add :: "+gold_ad);
        //selenium.isTextPresent(search1);
        //a[contains(text(),'Shaffer Dan & Diana')]
        //li[@id='divInAreaSummary_2']/div[2]/div[1]/h2/a
        /*for(int i=1; i<=10; i++){
            boolean gold_add = selenium.isElementPresent("//li[@id='divInAreaSummary_"+ i +"']/div[6][@class=\"adFlag-gold\"]");
            boolean business_listing = selenium.isTextPresent("//li[@id='divInAreaSummary_"+ i +"']/div[2]/div[1]/h2/a[contains(text(),"+ search1 +")]");
            System.out.println("************* "+ i +"***************" + search1);
            System.out.println("Gold Add :: "+gold_add +" Businessh Listing ::"+business_listing);
            System.out.println("******************************");*/
       
       
        if (selenium.isTextPresent(search1)) {
           
                boolean gold_ad = selenium.isElementPresent("//div[@class=\"adFlag-gold\"]");
                boolean text = selenium.isElementPresent("//a[contains(text(),search1)]");
                System.out.println("Gold_add :: " + gold_ad);
                System.out.println("text :: " + text);
                   
                verifyTrue(selenium
                        .isElementPresent("//div[@class=\"adFlag-gold\"]"));
               
                           } else {
                //assertTrue(selenium.isElementPresent(search1));
                System.out.println("element not found");
            }
       
       
       


    }

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

    public String[][] getTableArray(String xlFilePath, String sheetName,
            String tableName) throws Exception {
        String[][] tabArray = null;

        Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
        Sheet sheet = workbook.getSheet(sheetName);
        int startRow, startCol, endRow, endCol, ci, cj;
        Cell tableStart = sheet.findCell(tableName);
        startRow = tableStart.getRow();
        startCol = tableStart.getColumn();

        Cell tableEnd = sheet.findCell(tableName, startCol + 1, startRow + 1,
                100, 64000, false);

        endRow = tableEnd.getRow();
        endCol = tableEnd.getColumn();
        System.out.println("startRow=" + startRow + ", endRow=" + endRow + ", "
                + "startCol=" + startCol + ", endCol=" + endCol);
        tabArray = new String[endRow - startRow - 1][endCol - startCol - 1];
        ci = 0;

        for (int i = startRow + 1; i < endRow; i++, ci++) {
            cj = 0;
            for (int j = startCol + 1; j < endCol; j++, cj++) {
                tabArray[ci][cj] = sheet.getCell(j, i).getContents();
            }
        }

        return (tabArray);
    }

}// end of class
The Excel sheet has to be placed in the path which is been specified in the DP1 dataprovider 
"test\\Resources\\Data\\Book1.xls", "DataPool", "yellowbook"

How to Handle SSl certifications .

At times when we automate some Webpages with SSL Certifications we get a XHR error in RC .
Steps to over come is :
Step 1: Go to Run-----> firefox -p
Step 2 : Create a New Firefox Profile Template .
Step 3 : Now u need to install an SSL Add on .
Step 4 : Add the certification exception onto that profile .
Now when u run your scripts from RC it will work fine .

How to parametrize the values in the Testng

package smoke;

import com.thoughtworks.selenium.*;

//import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.RemoteControlConfiguration; //import org.openqa.selenium.server.SeleniumServer;

import org.testng.annotations.*;

public class Popup extends SeleneseTestCase {
String trafficOutput;
public static Selenium selenium;
public static final String MAX_WAIT_TIME_IN_MS = "30000";

    boolean Condition = true;

    @BeforeSuite
    @Parameters( { "selenium.host", "selenium.port", "selenium.browser","selenium.url" })
    public void setUp(String host, String port, String browser, String url)
            throws Exception {

        RemoteControlConfiguration rc = new RemoteControlConfiguration();
        rc.setSingleWindow(true);
        rc.trustAllSSLCertificates();

        selenium = new DefaultSelenium(host, Integer.parseInt(port), browser,url);

        selenium.start();
   
        selenium.windowMaximize();
    }


This is how ur main program will look like and the XMl file where u can declare the parameters 


<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">

<suite name="test"  parallel="tests"  threadcount="5" >
<parameter name="selenium.host" value="localhost"></parameter>
<parameter name="selenium.port" value="4444"></parameter>
<parameter name="selenium.browser" value="*firefox"></parameter>
<parameter name="selenium.url" value="https:"></parameter>

<test name="test1" >
<classes>
<class name="smoke.Popup" />
</classes>
</test>

</suite>