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

Friday, April 12, 2013

Selenium: Find greatest of 3 nos

 Find the greatest of 3 nos



import javax.swing.JOptionPane;

public class Greatest_of_3_nos
{

 public static void main(String[] args)
 {
  int a,b,c;
  a=Integer.parseInt( JOptionPane.showInputDialog("Enter an value of a"));
  b=Integer.parseInt(JOptionPane.showInputDialog( "Enter an value of b"));
  c=Integer.parseInt(JOptionPane.showInputDialog( "Enter an value of c"));

  if (a > b && a > c)
  {
   System.out.print(a+" is the greatest");
  }
  else if  (c > b && a < c)
  {
   System.out.print(c+" is the greatest");
  }
  else
  {
   System.out.print(b+" is the greatest");
  }

 }
} 

Selenium : To calculate age of a person

                                                    To calculate age of a person



import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;

public class Calculate_age
{
 public static void main(String[] args)
 {
  Date oDt=new Date();
  int iYear=Integer.parseInt(JOptionPane.showInputDialog(null, "Enter birth year"));
  JOptionPane.showMessageDialog(null,(oDt.getYear()+1900)- iYear);  
 }
}
 

Selenium : Validate voters age

Program to check the age of user


import javax.swing.JOptionPane;
public class Vote_eligible {
 public static void main(String[] args)
 {
  int iAge=Integer.parseInt(JOptionPane.showInputDialog("enter age"));
  if (iAge>= 18)
  {
   JOptionPane.showMessageDialog(null, "Voter is above or equal to 18 years ,Elibible to vote");
  }
  else
  {
   JOptionPane.showMessageDialog(null, "Voter not eligible to vote");
  }   

 }
}

Selenium:Get Month Name (Using Select Case and Array)

 Display Current Month Name using Array and Select Case




import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class Month_Name
{

 public static void main(String[] args)
 {
  Date dt=new Date();
  System.out.println(dt.getMonth());

  String Month_Name[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};

  switch (dt.getMonth())//(c.MONTH+1)
  {
  case 0:
   System.out.println(Month_Name[0]);
   break;
  case 1:
   System.out.println(Month_Name[1]);
   break;
  case 2:
   System.out.println(Month_Name[2]);
   break;
  case 3:
   System.out.println(Month_Name[3]);
   break;
  case 4:
   System.out.println(Month_Name[4]);
   break;
  case 5:
   System.out.println(Month_Name[5]);
   break;
  case 6:
   System.out.println(Month_Name[6]);
   break;
  case 7:
   System.out.println(Month_Name[7]);
   break;
  case 8:
   System.out.println(Month_Name[8]);
   break;
  case 9:
   System.out.println(Month_Name[9]);
   break;
  case 10:
   System.out.println(Month_Name[10]);
   break;
  case 11:
   System.out.println(Month_Name[11]);
   break;
 
  }

 }

}
 

Tuesday, April 9, 2013

Selenium :Extracting Date from input string or putting date in particular format

                           Accepting String calender data and extracting date



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//to create a SimpleDateFormat object and use it to parse Strings to Date and
//to format Dates to Strings. If you've tried SimpleDateFormat and it didn't work, then please show your code and any errors you may receive.
//
//Addendum: "mm" in the format String is not the same as "MM". Use MM for months and mm for minutes. Also, yyyyy is not the same as yyyy.

public class Changing_Date_Format
{

 public static void main(String[] args) throws ParseException
 {
  String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss" 
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s); //Converting String to Date

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));

 }
}

Selenium : Date

To Demonstrate date function



import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class Month_Name
{

 public static void main(String[] args)
 {
  Date dt = new Date();
  System.out.print(dt.toString());
  System.out.println(dt.getMonth()+":"+dt.getDate()+":"+dt.getYear());

  Calendar c = new GregorianCalendar();
  System.out.println(c.getTime());
  System.out.println(c.DATE+"/"+c.MONTH+"/"+c.YEAR);
 }

}

Selenium : Datatype Conversions

 Datatype Conversions

 //To demonstrate DataType conversions



public class Convert_2_int
{

 public static void main(String[] args)
 {
  String s="123";
  int a=Integer.parseInt(s);
  Float b=Float.parseFloat(s);
  System.out.println(a);
  System.out.println(b);
 }

}

Selenium : Basic arithematic operations and Insert Spaces

Basic arithematic operations



//To demonstrate the use of all arithematic operators
//Inserts 2 spaces   -     String.format("%2s","")

public class All_Arithematic_Operators
{

 public static void main(String[] args)
 {
  System.out.println(1+2);
  System.out.println(1-2);
  System.out.println(1/2);
  System.out.println(1*2);
  System.out.println(Math.sqrt(2));

  int a=1,b=2;
  if (a==1 && b==2 )
  {
   System.out.println("a==1 && b==2"+String.format("%2s","")+"true --a="+a+" b="+b);//Insert spaces
  }
  if (a!=2 || b!=1 )
  {
   System.out.println("a!=2 || b!=1"+String.format("%2s","")+"true --a="+a+" b="+b);//Insert Spaces
  }

  if (a < b)
  {
   System.out.println("a < b"+String.format("%2s","")+"true --a="+a+" b="+b);//Insert Spaces
  }
  if (a <= b)
  {
   System.out.println("a <= b"+String.format("%2s","")+"true --a="+a+" b="+b);//Insert Spaces
  }

 }

}

Thursday, April 4, 2013

Selenium : Initialising Objects

Initialising Objects

Example to open the browser and click on the Search button .


public class Test
{
 public static void test1() 
 {
  FirefoxDriver oFx=new FirefoxDriver ();   
  EventFiringWebDriver oEvent=new EventFiringWebDriver(oFx);
  oEvent.get("
http://www.google.co.in/");
  Thread.sleep(1000);

  WebElement oButton=oEvent.findElement(By.id("gbqfbb"));  //Object initialising
  oButton.click();
  System.out.print("Fin");

  oEvent.close();
  oEvent.quit();
}
}

Selenium : Verify element - 1. ispresent 2. isvisible 3. isenable 4. textpresent

Selenium : Verify element - 1. ispresent 2. isvisible 3. isenable 4. textpresent


  1. To check Element Present:
    if(driver.findElements(By.xpath("value")).size() != 0){
    System.out.println("Element is Present");
    }else{
    System.out.println("Element is Absent");
    }
    
    Or
    if(driver.findElement(By.xpath("value"))!= null){
    System.out.println("Element is Present");
    }else{
    System.out.println("Element is Absent");
    }
    
  2. To check Visible:
    if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){
    System.out.println("Element is Visible");
    }else{
    System.out.println("Element is InVisible");
    }
    
  3. To check Enable:
    if( driver.findElement(By.cssSelector("a > font")).isEnabled()){
    System.out.println("Element is Enable");
    }else{
    System.out.println("Element is Disabled");
    }
    
  4. To check text present
    if(driver.getPageSource().contains("Text to check")){
    System.out.println("Text is present");
    }else{
    System.out.println("Text is absent");
    }
  5. WebElement rxBtn = driver.findElement(By.className("icon-rx"));
    WebElement otcBtn = driver.findElement(By.className("icon-otc"));
    WebElement herbBtn = driver.findElement(By.className("icon-herb"));
Assert.assertEquals(true, rxBtn.isDisplayed());
Assert.assertEquals(true, otcBtn.isDisplayed());
Assert.assertEquals(true, herbBtn.isDisplayed()); 

6. driver.findelement(By.id("id1")).isDisplayed()
  driver.findelement(By.id("id2")).sendkey("test"); 


Example :
 protected boolean isElementPresent(By by)
 {
   try {
    driver.findElement(by);
    return true;
       }
   catch (NoSuchElementException e)
  {
    return false;
  }
}
 

Sunday, March 24, 2013

Selenium:Open Browser and Check for element..BETTER !!

Open Browser and Check for element..BETTER !!


import javax.swing.JOptionPane;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Sample1
{
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.firefox.bin","E://Work//Program_files//Firefox17.0//firefox.exe");
FirefoxDriver oDriver=new FirefoxDriver();
oDriver.get("http://yahoo.com");

if (oDriver.findElementByXPath("//*[@id='default-u_14119506-bd']/div/h1/span").isDisplayed()==true)
{
System.out.println("passed");
}
else
{
System.out.println("failed");
}

// String a=JOptionPane.showInputDialog(null,"What is your name ?");
Thread.sleep(5000);
oDriver.close();
oDriver.quit();
JOptionPane.showMessageDialog(null,"Done");

}
}

Selenium:Open browser and Check for element

Open browser and Check for element




import javax.swing.JOptionPane;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Sample1
{
public static void main(String[] args) throws InterruptedException
{
//WebDriver driver = new FirefoxDriver(new FirefoxBinary(new File("path/to/your/firefox.exe")), profile);
System.setProperty("webdriver.firefox.bin","E://Work//Program_files//Firefox17.0//firefox.exe");
FirefoxDriver oDriver=new FirefoxDriver();
oDriver.get("http://yahoo.com");
//oDriver.
try
{
WebElement oflag=oDriver.findElementByXPath("//*[@id='default-u_14119506-bd']/div/h1/span") ;
System.out.println("passed");
}catch(org.openqa.selenium.NoSuchElementException Ex)
{
System.out.println("failed");
}

JOptionPane.showMessageDialog(null,"Done");

//driver.findElement(By.id("...")).isDisplayed()
// String a=JOptionPane.showInputDialog(null,"What is your name ?");
// JOptionPane.showMessageDialog(null, a);
Thread.sleep(5000);
oDriver.close();
oDriver.quit();

}
}

Wednesday, February 27, 2013

Selenium :Assersions (Skipping @Test after a Step Fails )

 

Assersions

 

  • assertTrue will fail if the second parameter evaluates to false (in other words, it ensures that the value is true). 
  • assertFalse does the opposite.
Example:
assertTrue("This will succeed.", true);
assertTrue("This will fail!", false);

assertFalse("This will succeed.", false);
assertFalse("This will fail!", true);









Important Types :
  1.     Assert.assertequals("good","god");         o/p: Failed
  2.     Assert.assertTrue("Message " ,4>8 );     o/p-Failed     some message
  3.     Assert.assertFalse("Message " ,8<9 );    o/p-Failed     some message

Note : RunAs>TestNg

Advantages :
Used to report Pass and Fail

Disadvantage:
I have illustrated with the example below.

The file contains 2 @Test ,one having "Assert" statement .If the control encounters failure from Assert statement,then the control will report failure, Skip all the following lines in the current test and jump to the next test.

Overcome :
Use Listerners


//------------------------------------------------------------------------------------------------
package package_name;

import org.testng.Assert;

import org.testng.SkipException;

import org.testng.annotations.BeforeMethod;

public class Test

{

@org.testng.annotations.Test

public void test1()

{

Assert.assertEquals(1, 2);

System.out.println("Testing 1");

}

@org.testng.annotations.Test

public void test2()

{

System.out.println("Testing 2");

}

}

Selenium : Throw new SkipException


Program to skip all the tests in a file using "Throw new SkipException". The below file contains 2 @Test which is test1 ,test2 and we have @BeforeMethod. By inserting "Throw new SkipException" statement in the @BeforeMethod all the test can be skipped while executing through TestNG.


Example :

package package_name;

import org.testng.SkipException;
import org.testng.annotations.BeforeMethod;


public class Test
{

@BeforeMethod
public void Method()
{
System.out.println("BeforeMethod");
throw new SkipException ("Skipping test");//Instruction to Skip
}

@org.testng.annotations.Test
public void test1()
{
System.out.println("Testing 1");
}

@org.testng.annotations.Test
public void test2()
{
System.out.println("Testing 2");
}

}

Selenium :Java Constructor Example

Constructor

  

public class Car
{
String mod;
int price;
public Car (String mod)
{
mod=mod;
//price=price;
}
public Car (String mod, int price )
{
this.mod=mod;
this.price=price;
}
public static void main(String[] args)
{
Car c1=new Car("Constructor 1");
System.out.println(c1.mod);
Car c2=new Car ("Constructor 2",10000);
System.out.println(c2.mod+"---"+c2.price);

}

}

Tuesday, February 26, 2013

Selenium: Parameterization

Parameterization

  1. TestNg should be installed before execution.
  2. Runas>TestNg



package package_name;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class Parameter
{

@Test (dataProvider = "registerData")
public void SampleTest1A(String US,String Pass,String Id ,String name)
{
System.out.println(US+ "--"+Pass+ "--"+Id+ "--"+name);
}
@DataProvider
public Object[][] registerData()
{
Object[][] Data=new Object[3][4];//execute 3 Times , 4 Data Series taking 1 series each time
//Rows = No of times test should be repeated
//Columns = No of data
Data[0][0]="US1";
Data[0][1]="Pass1";
Data[0][2]="ID1";
Data[0][3]="Name1";
Data[1][0]="US2";
Data[1][1]="Pass2";
Data[1][2]="ID2";
Data[1][3]="Name2";
Data[2][0]="US3";
Data[2][1]="Pass3";
Data[2][2]="ID3";
Data[2][3]="Name3";

return Data;
}

}

Thursday, February 21, 2013

Selenium : Import One Java file into another


Residing in Same package:

Example : 

 In the below example Sample1 is using a variable from OR , here there is no need to import any file as both files are residing in the same package , hence can be directly called .

------------------------File Name : Sample1 --------------------File1
public class Sample1
{
    public static void main(String[] args)   
    {       
        WebDriver oDriver=new FirefoxDriver();
        oDriver.get("https://www.google.co.in");
        WebElement oTitle=oDriver.findElement(By.xpath(OR.button));  // Directly using the static variable
    }
}
===================================================================

------------------------File Name : OR --------------------File2
public class OR {

   
        public static final String button="//button[@id='gbqfba']";
       

}
===================================================================


Residing in Different package:

One Java file can be imported into another by using "Package" keyword .

To do this a new package has to be created with Java files to be used, residing inside .In the below eg "File_StringCheck.java" is residing inside the package "utilityfunction" .Hence the below code can access the methods from "File_StringCheck.java" by  import Utilityfunction.

Eg :

import Utilityfunction.File_StringCheck;
package Utilityfunction;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.swing.JOptionPane;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


import jxl.*;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;
import jxl.read.biff.BiffException;
import jxl.write.*;
import java.util.Date;



 
public class Test{
{





}
}

Selenium :To goto google.apps and get corresponding app name , downloaded times ,ratings .

Program to goto google.apps and get corresponding app name , downloaded times , ratings and update it in a excel file with TimeStamp .


Here we are doing following things :-
1.Read Data from Input Excel Sheet
2.Search the data in the input excel and store it in an array.
3.Create a new excel sheet with Time stamp.
4.Insert the gathered info into the newly created excel.

 

The data (i.e., the app to search )is fed using excel  Eg-"D:\\Selenium\\test\\test.xls";

EX :
NFS
AngryBirds



Format in Input Excel:
r1c1         r1c2        r1c3      r1c4   -----Column Names
Input      appname      stars   downloaded

r2c1       r2c2         r2c3       r2c4
 Nfs


r3c1       r3c2         r3c3       r3c4
AngryBirds




//package Utilityfunction;


import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.swing.JOptionPane;


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


import jxl.*;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;
import jxl.read.biff.BiffException;
import jxl.write.*;
import Utilityfunction.File_StringCheck;
import java.util.Date;



public class Test
{

public static void main(String[] args) throws BiffException, IOException, WriteException
{
//
String sSrc="D:\\Selenium\\test\\test.xls";
String sDest="D:\\Selenium\\test\\test_"+Time_stamp()+".xls";
int iRows,i,j,iCols;
String[] aRes;
Label Llabel;

Workbook workbook1 = Workbook.getWorkbook(new File(sSrc));
iRows=workbook1.getSheet(0).getRows();//-1;
iCols=workbook1.getSheet(0).getColumns();//-1; //getRows()-1;
String[][] App_data=new String[iRows][iCols];
Sheet oSheet1=workbook1.getSheet(0);

for ( i=0 ; i<=oSheet1.getRows()-1;i++)
{
for ( j=0 ; j<=oSheet1.getColumns()-1;j++)
{
App_data[i][j]=oSheet1.getCell(j, i).getContents();


}
}
workbook1.close();

WebDriver driver= new FirefoxDriver();
driver.get("https://play.google.com/store");
for ( i=1 ; i<=iRows-1 ;i++)
{
driver.findElement(By.id("search-text")).sendKeys(App_data[i][0]);//("nfs");
driver.findElement(By.id("search-button")).click();
aRes=(mData(driver)).split(";");
for (j=0 ; j<=aRes.length-1 ; j++)
{
App_data[i][j+1]=aRes[j];
}

driver.findElement(By.id("search-text")).clear();
}

WritableWorkbook workbook2 = Workbook.createWorkbook(new File(sDest));//, workbook1);
WritableSheet oSheet2 = workbook2.createSheet("First Sheet", 0);
for ( i=0 ; i<=App_data.length-1;i++)
{
for ( j=0 ; j<=App_data[0].length-1;j++)
{
Llabel = new Label(j, i, App_data[i][j]);
oSheet2.addCell(Llabel);
}
}
workbook2.write();
workbook2.close();
System.out.println("over");
driver.quit();
System.exit(0);
}


public static String Time_stamp() //TimeSatmp
{
//java.util.Date date = new java.util.Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return (((dateFormat.format(date)).replace("/", "_")).replace(":", "_")).replace(" ", "_");
}

public static String mData(WebDriver oBrowser)
{
if (oBrowser.getCurrentUrl().contains("https://play.google.com/store/search") == false)
{
System.out.println("Not in the website");
return "0";
}

String sApp_name=oBrowser.findElement(By.xpath("//li[1]/div/div[2]/a")).getText();
String sStars=oBrowser.findElement(By.xpath("//li[1]/div/div/div/div/div")).getAttribute("title");
String sDownloads=oBrowser.findElement(By.xpath("//li[1]/div/div[2]/div[2]//span")).getText();

return (sApp_name+";"+sStars+";"+sDownloads);
}
}

Wednesday, February 20, 2013

Selenium: Copy data from one Excel Sheet to another

Program to Copy 1 Data from 1 Excel to another



import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.swing.JOptionPane;
import jxl.*;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.biff.RowsExceededException;
import jxl.read.biff.BiffException;
import jxl.write.*;
import Utilityfunction.File_StringCheck;
import java.util.Date;



public class Test
{

public static void main(String[] args) throws BiffException, IOException, WriteException
{
String sTS=Time_stamp();
//String sSrc=
msExcel_Copy_File("D:\\Selenium\\test\\test.xls", "D:\\Selenium\\test\\test_"+sTS+".xls", "Sheet1", "Sheet1");
//System.out.print(;//("D:\\Selenium\\test\\output_"+sTS+".xls"), workbook);
}

public static String Time_stamp()
{
//java.util.Date date = new java.util.Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return (((dateFormat.format(date)).replace("/", "_")).replace(":", "_")).replace(" ", "_");

}

public static boolean msExcel_Copy_File(String sSrc_File , String sDest_File ,String sSrc_Sheet,String sDest_Sheet) throws BiffException, IOException, RowsExceededException, WriteException
{
String sTemp;
Label Llabel;
Workbook workbook1 = Workbook.getWorkbook(new File(sSrc_File));
Sheet oSheet1=workbook1.getSheet(sSrc_Sheet);

WritableWorkbook workbook2 = Workbook.createWorkbook(new File(sDest_File), workbook1);
WritableSheet oSheet2 = workbook2.getSheet(sDest_Sheet);


for (int i=0 ; i<=oSheet1.getRows()-1;i++)
{
for (int j=0 ; j<=oSheet1.getColumns()-1;j++)
{
sTemp=oSheet1.getCell(j, i).getContents();
Llabel = new Label(j, i, sTemp);
oSheet2.addCell(Llabel);
}
}
workbook2.write();
workbook2.close();
workbook1.close();
return true;
}


}