Tuesday, 5 August 2014

Printing the drop down values without using 'Select' class&Hidden vales of drop down

driver.get("http://www.facebook.com");
  // This will return 13 webelemenst
     List<WebElement> l1= driver.findElements(By.xpath("//*[@id='month']/option"));
      // Now using we will iterate using iterator
        Iterator<WebElement> i1=l1.iterator();      
        while(i1.hasNext()){      
        // Here we are capturing text using getText
        String value=i1.next().getText();      
        System.out.println(value);
=====+++++++++++++=====OR
 String e=driver.findElement(By.xpath("//*[@id='splitterid']")).getText();
System.out.println(e);

+++++++++++++++
wd.get("http://jqueryui.com/autocomplete/#combobox"); 
wait.until(ExpectedConditions.visibilityOf(wd.findElement(By.xpath(".//*[@id='content']/iframe")))); 
wd.switchTo().frame(wd.findElement(By.xpath(".//*[@id='content']/iframe"))); 
wd.findElement(By.cssSelector(".ui-button.ui-widget.ui-state-default.ui-button-icon-only.custom-combobox-toggle.ui-corner-right")).click();

WebElement combobox = wd.findElement(By.id("combobox")); 
List<WebElement> options = new Select(combobox).getOptions(); 
for (WebElement webElement : options) 

System.out.println("> " + webElement.getAttribute("value")); 


++++++++++++++++++++drop down desabled text++++++++
WebDriverWait wait = new WebDriverWait(driver, 60);
System.out.println("Waiting for Select"); 
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='shipping-info']/div/form/div[1]/div/div[2]/div[3]/div/div[4]/div[2]/div/div/a"))); 
Thread.sleep(10000); 
System.out.println("Selecting State"); 
driver.findElement(By.xpath("//*[@id='shipping-info']/div/form/div[1]/div/div[2]/div[3]/div/div[4]/div[2]/div/div/a")).click(); 
Thread.sleep(10000); 
action.sendKeys("California").build().perform(); 
Thread.sleep(500); 

action.sendKeys(Keys.TAB).build().perform(); 

Wednesday, 30 July 2014

Jobs scheduling using 'task schedular'

open 'task scheduler' fron start menu
right click on 'task schedular library'
click on create task
On 'genara' tab give any name, give some descrition
go to 'trigger' tab, click 'new' , select time as per ur requirement
click ok
go to 'actions' tab
clik on 'new', here u need to give batch file path.clik ok, then over.

Selenium test execution video record(long time)

Video Record Selenium Tests


ScreenRecoder supports “AVI” and “QuickTime” format for recording the video. For “AVI” format you need to install TSCC Codec (Techsmith Screen Capture Codec) while “QuickTime” format is supported by Apple’s QuickTime Player. ScreenRecorder provides multiple configurations for colors, mouse cursor, screen rate, mouse rate, audio etc. on GUI as well as programmatically.
1| Download MonteScreenRecorder.jar from google.
2| Add MonteScreenRecorder.jar into buildpath
3| Locate startRecording() and stopRecording() on apt location
4| Run the test
5| After finishing testrun check the location, C:\Users\username\Videos for recorded video, "ScreenRecording 2013-10-18 at 15.01.43.avi"
import java.awt.*;
import org.monte.media.Format;
import org.monte.media.math.Rational;
import static org.monte.media.AudioFormatKeys.*;
import static org.monte.media.VideoFormatKeys.*;
import org.monte.screenrecorder.ScreenRecorder;

public class className {
private ScreenRecorder screenRecorder;

@Test
public void test01() throws Exception {
className videoRecord = new className();
videoRecord.startRecording(); //Started recording
driver.get("www.xyz.com");
Thread.sleep(2000);
videoRecord.stopRecording(); //Stopped recording

}


 public void startRecording() throws Exception
    
GraphicsConfiguration gc = GraphicsEnvironment
              .getLocalGraphicsEnvironment()
              .getDefaultScreenDevice()
              .getDefaultConfiguration();

this.screenRecorder = new ScreenRecorder(gc,
              new Format(MediaTypeKey, MediaType.FILE, MimeTypeKey, MIME_AVI),
              new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                   CompressorNameKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
                   DepthKey, 24, FrameRateKey, Rational.valueOf(15),
                   QualityKey, 1.0f,
                   KeyFrameIntervalKey, 15 * 60),
              new Format(MediaTypeKey, MediaType.VIDEO, EncodingKey, "black",
                   FrameRateKey, Rational.valueOf(30)),
              null);
this.screenRecorder.start();   
}

public void stopRecording() throws Exception
{
this.screenRecorder.stop();

}

Thursday, 24 July 2014

Reading and Writing data from excel using 'poi'(xlsx)


Step 1: First u need download 'poi' related all jars and set up these jars files in ur eclipse.
Step 2: just write the below code
//Readig data from excel using poi and writng in to another excel file in java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class DDT_1_Java_Run {

public static void main(String[] args) throws IOException {
File src=new File("TestData.xlsx");
FileInputStream fis=new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh=wb.getSheetAt(0);
//getRow specify which row we want to read and getCell which column
System.out.println(sh.getRow(0).getCell(0).getStringCellValue());
System.out.println(sh.getRow(1).getCell(0).getStringCellValue());
sh.getRow(0).createCell(2).setCellValue(11);
sh.getRow(0).createCell(3).setCellValue(12);
FileOutputStream fo=new FileOutputStream("output.xlsx");
wb.write(fo);
fo.close();
}

}
2nd code: using for loop

public class DDT_2_Sele
{

public static void main(String[] args) throws InvalidFormatException, IOException {
// File src=new File("\test\\Test2.xlsx");
// FileInputStream fis=new FileInputStream(src);
Workbook wb=WorkbookFactory.create(new FileInputStream("\test\\Test2.xlsx"));
Sheet sh=wb.getSheetAt(0);
int rows=sh.getLastRowNum();
for(int i=0;i<rows+1;i++)
{
String data1=sh.getRow(i).getCell(0).getStringCellValue();
String data2=sh.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data from 1st column and row:"   +  data1);
System.out.println("Data from 1st column and row:" + data2);
}

}

}

Wednesday, 23 July 2014

Log4j properties file

 Open notepad and copy the below code and save the file as log4j.properties

Note- Please create the log folder inside home directory

// Here we have defined root logger
log4j.rootLogger=INFO,CONSOLE,R,HTML,TTCC

// Here we define the appender
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.TTCC=org.apache.log4j.RollingFileAppender
log4j.appender.HTML=org.apache.log4j.FileAppender

// Here we define log file location
log4j.appender.R.File=./log/testlog.log
log4j.appender.TTCC.File=./log/testlog1.log
log4j.appender.HTML.File=./log/application.html

// Here we define the layout and pattern
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= %5p [%t] (%F:%L)- %m%n
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c -%p - %m%n
log4j.appender.TTCC.layout=org.apache.log4j.TTCCLayout
log4j.appender.TTCC.layout.DateFormat=ISO8601
log4j.appender.HTML.layout=org.apache.log4j.HTMLLayout
log4j.appender.HTML.layout.Title=Application log
log4j.appender.HTML.layout.LocationInfo=true

Wednesday, 16 July 2014

Record(video) selenium test execution report

we need to record test execution and review the video after the execution has finished.
This is especially important if you run unattended tests on a different machine and find out about failed tests after the event.
Step 1: download jar from "https://drive.google.com/folderview?id=0B7rZvkq9tkwPRy1HLVJCdWtNekE&usp=sharing"
What additional work you have to do for this?
Ans: You just have to add 3 lines of code for
Setting up a recorder
Starting the recorder
Stopping the recorder


Sample script:
package Record;

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

import atu.testrecorder.ATUTestRecorder;
import atu.testrecorder.exceptions.ATUTestRecorderException;

public class Class1 {
static WebDriver driver;
public static void main(String[] args) throws ATUTestRecorderException {
//Here need to give file location and file name
ATUTestRecorder recorder = new ATUTestRecorder("D:\\sws","practice",false);
recorder.start();

//public static void main(String[] args) {


driver = new FirefoxDriver();
driver.navigate().to("http://www.w3schools.com/ajax/ajax_database.asp");
driver.manage().window().maximize();
driver.quit();
recorder.stop();

}
}
Run the test case 
see video from location where u stored.

Friday, 11 July 2014

Generating Xslt reports using ant and testng

Generate XSLT Report(Advanced HTML Report) in Selenium
XSLT stands for XML Style-sheet language for transformation,It provide very rich formatting report using TestNG framework
Precondition-
1- Ant should be installed if not please install using below post
Install ANT
2- At-least one testcase should be executed by TestNg (i.e we should have test-output directory available in home directory)
Step 1- Download XSLT from "https://drive.google.com/folderview?id=0B5v_nInLNoquV1p5YWtHc3lkUkU&usp=sharing"
Step 2- Unzip this and copy all the files and paste into project home directory.
add all files in to project , 'not under src folder'
Step 3- Run build.xml using Ant - To run build.xml file
To check whether the 'ant' installed properly or not
Open CMD and go till project directory and type 'ant' run and hit enter.
To genarate xslt reports using cmd prompt
open cmd prompt, go to project folder, 'not in src folder' and type 'ant generateReport' and hit enter
Step 4- Once build successful then type 'ant generateReport' and hit enter again
Step 5- Once build successful then go to project directory and you will get testng-xslt folder

Inside testng-xslt you will get index.html (this is the main report) open in FF or in Chrome

***reference urls
http://www.learn-automation.com/2014/06/generate-xslt-reportadvanced-html.html

Log4j configuration for java(selenium) projects in eclips

Step 1:
Log4j is open source tool given by apache for creating log files It help us to generate log file in various output target.

Step2: Download Log4j from " http://mirrors.ibiblio.org/pub/mirrors/maven/log4j/jars/log4j-1.2.15.jar"
Step 3: add this jar file in to eclipse
Select your project > Right click > Click on build path> Click Configure build path> Go to library section > Add external jar file > select the log4j > click on save.
Step 4:
Open notepad and copy the below code and save the file as log4j.properties, it looks like


Step 5- Write test case

import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Google {
    public static void main(String[] args) {
      
    // Here we need to create logger instance so we need to pass Class name for which we want to create log file in my case Google is classname
         Logger logger=Logger.getLogger("Google");
        
       PropertyConfigurator.configure("Log4j.properties");

        WebDriver driver = new FirefoxDriver();
        logger.info("Browser Opened");
      
      
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        logger.info("Implicit wait given");
      
        driver.get("https://www.google.co.in/");
        logger.info("Url opened");
      
        driver.findElement(By.name("q")).sendKeys("Selenium");
        logger.info("keyword type");           
    }
}


Step 6- Run your test case and verify the output and log files as well

Here is the log files


Note: The folder structure should be like below
 MyProject
       src
           MyClass.java
           log4j.properties

Thursday, 10 July 2014

Working with different languages

How to change the language preferences in Selenium Webdriver

Before moving to language preference lets talk about why it is required and why we are changing this ?

1-Some time in real time you will face some situation where you need to check whether your application support multiple languages or not. In other words your application is globally working or not.

2-To check this we can change the language preference and open the same application with that language so if your application support that particular language it will open the  application the same language and if not supported then by default it will open in English.

For Example- Open Google in Chinese and Facebook in Chinese so if they support Chinese language so  both application will open in Chinese language

To implement this we need to change the browser setting to achieve this we can use FirefoxProfile class  and setPreferences method

Scenario - Open Google in  Chinese language and verify the total page translated or not.

To check these setting you can open firefox browser and in url type about : config


Now check the properties which we need to change in this scenario we need to modify intLaccept_languages and by default it set to en (English)




Let's implement the same in Selenium Webdriver


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.Test;


public class TestFFLangua {


@Test
public void testFFP(){

// This will create firefox profile
FirefoxProfile fp=new FirefoxProfile();

               // this will change the language preference and zh is the locale for China
fp.setPreference("intl.accept_languages", "zh");
           
                // now pass this fp object to FirefoxDriver
WebDriver driver=new FirefoxDriver(fp);

driver.manage().window().maximize();

driver.get("https://www.facebook.com");


}

}

DataBase Testing using Excel

Step 1: Download fillo from http://www.codoid.com/products/view/2/29/validEmail
Step 2: Enter your valid email
Step 3: Download the fillo file and add jar to excipse work space

About FILLO:
Fillo is an Excel API for Java and you can query xls & xlsx files. Now, it supports SELECT, UPDATE & INSERT queries with or without WHERE clause. 
Example Scenario:
26. Consider an excel sheet having data of employee table 
EmpName Salary
Emp1 100
Emp 2 400
Emp 3 500
Emp 4 200
Emp 5 100
How will you read the excel sheet, check the condition that salary>100 and print all the emp names 

For Select:
Fillo fillo=new Fillo();

Connection connection=fillo.getConnection("C:\\Test.xlsx");

String strQuery="Select * from Sheet1 where Salary=100";

Recordset recordset=connection.executeQuery(strQuery);
while(recordset.next()){

System.out.println(recordset.getField("EmpName"));
}
 

recordset.close();

connection.close();++++++for update++++++public class Db_Excal_Fillo {public static void main(String args[]) throws FilloException{ Fillo fillo=new Fillo(); Connection connection=fillo.getConnection("C:\\v2autoW5.0\\Test\\src\\info\\e2e_zonal\\DbTest.xls"); String strQuery="Update Sheet1 Set Salary='1000' where Salary=100";   connection.executeUpdate(strQuery);   connection.close(); =========Insert+++++
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("C:\\Test.xlsx");
String strQuery="INSERT INTO sheet4(Name,Country) VALUES('Peter','UK')";
connection.executeUpdate(strQuery);

connection.close();---------------

Where method


Recordset recordset=connection.executeQuery("Select * from Sheet1").where("ID=100").where("name='John'");

Set row and column

//Now you can set table start row and column

System.setProperty("ROW""5");//Table start row

System.setProperty("COLUMN""3");//Table start column

Fillo fillo=new Fillo();
Connection connection=fillo.getConnection(strFile);