Groovy in SOAP UI
Note: In groovy script is invoked with log, context and testRunner (Case sensitive) variables
1.To Print anything:
log.info "hello"
def x="Myname"
log.info x
log.info "Starting the test"
log.error "An error has occured while execution"
log.info "ending the test"
2.Setting the properties at different levels:
project Level:
testRunner.testCase.testSuite.project.setPropertyValue("projectproperty","projectpropertyvalue")
Test Suite level:
testRunner.testCase.testSuite.setPropertyValue("suiteproperty","suitepropertyvalue")
Test Case Level:
testRunner.testCase.setPropertyValue("testcaseproperty","propertyvalue")
Global level:
com.eviware.soaupui.SoapUi.getGloabalProperties.setGloabalProperyValue("globalproperty","gloabalpropertyvalue")
3.Retrieve the properties at different levels:
project Level:
testRunner.testCase.testSuite.project.getPropertyValue("projectproperty")
Test Suite level:
testRunner.testCase.testSuite.getPropertyValue("suiteproperty")
Test Case Level:
testRunner.testCase.getPropertyValue("testcaseproperty")
Global level:
com.eviware.soaupui.SoapUi.getGloabalProperties.setGloabalProperyValue("globalproperty")
4. Print the project,testsuite,testcase and test Step Name:
log.info testRunner.testCase.testSuite.project.name
log.info testRunner.testCase.testSuite.name
log.info testRunner.testCase.name
log.info context.getCurrentStep().name
5. Change the requestXml from groovy
def groovyutils=new com.eviware.soapui.support.GroovyUtils(context)
def holder= groovyutils.getXmlHolder("allplayersrequest#request)
holder["//foot:bselected"]="wales"
holder.updateProperty()
context.requestContext=holder.xml
6. Run a testcase located in another project
1st Way:
def prj=testRunner.testCase.testSuite.project.workspace.getProjectName("Module1")
tcase=prj.testSuites['TestSuite1'].testCases['TestCase1']
tstep=tcase.getTestStepByName("allplayersrequest")
def runner=tstep.run(testRunner,context)
log.info("runner Status.......:"+ runner.hasResponse())
7. Accessing property files
Properties prop=new Properties()
String path=System.getPorperty("user.dir") //this will give the path till bin dir of soapUI folder
def propfile= path +"\\test.properties"
FileInputStream fis=new FileInputStream(propfile)
prop.load(fis)
log.info prop.getProperty("Name")
log.info prop.getProperty("Address")
log.info prop.getProperty("Phone")
Note: property file should be in bin folder of souapui folder
property file looks something as below
Name=xyz
Address=address
Phone=00000
8. Accessing csv file
1st Method
import java.io.file
import java.io.FileNotFoundException
import java.util.Scanner
path=<<csv file path>>
File file=new File(path)
Scanner inputstream=new Scanner(file)
try
{
inputsteam.next()
while(inputstream.hasnext())
{
String d=inputstream.next()
log.info d
}
inputstream.close()
}catch(FileNotFoundException e){e.printStackTrace()}
2nd Method
def path=<<path of csv file>>
context.filereader=new BufferedReader(new FileReader(path))
File f=new File(path)
List lines=f.readLines()
int rows=lines.size()
for(int cntr:0..rows-1)
{
log.info lines[cntr]
}
9. Executing groovy file through groovy script
evaluate(new File("pathof groovyfile.groovy"))
10. Reading xls file
Precondtion: Copy the following jar in lib folder of SoauUI installation.
Say for example: C:\Program Files\SmartBear\SoapUI-5.2.1\lib
1.poi-3.6-20091214
2.poi-ooxml-3.6-20091214
3. poi-ooxml-schemas-3.6-20091214
4.xmlbeans-2.3.0
(The poi versions may not be same as mentioned above. That may vary with latest version releases)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
public class readxl{
public static XSSFWorkbook Excelworkbook;
public static XSSFSheet Excelworksheet;
public static XSSFCell Excelcell;
public static XSSFRow Excelrow;
public readxl(String fname)
{
try
{
FileInputStream fip=new FileInputStream(fname);
Excelworkbook=new XSSFWorkbook(fip);
}catch(Exception e){}
}
public static int getLastrow(String sheetname)
{
try
{
Excelworksheet=Excelworkbook.getSheet(sheetname);
int row=Excelworksheet.getLastRowNum();
return row;
}catch(Exception e){return -1}
}
public static String getCelldata(int rownum,int colnum)
{
try
{
Excelcell=Excelworksheet.getRow(rownum).getCell(colnum-1);
String cellval;
if(Excelcell.getCellType()==Excelcell.CELL_TYPE_STRING)
cellval=Excelcell.getStringCellValue();
else if(Excelcell.getCellType()==Excelcell.CELL_TYPE_NUMERIC)
cellval=String.value(Excelcell.getNumericCellValue());
else
cellval=null;
return cellval;
}catch(Exception e){return "";}
}
public static void setCelldata(String fname,String result,int RowNum,int ColNum)
{
CellStyle style=Excelworkbook.createCellStyle();
if(result.equalsIgnoreCase("pass"))
{
style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
}
else if(result.equalsIngnoreCase("fail"))
{
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
}
try
{
Excelrow = Excelworksheet.getRow(RowNum);
Excelcell = Excelrow.getCell(ColNum-1,Excelrow.RETURN_BLANK_AS_NULL);
if(Excelcell==null)
{
Excelcell=Excelrow.createCell(ColNum-1);
Excelcell.setCellValue(result);
Excelcell.setCellStyle(style);
}else{
Excelcell.setCellValue(result);
Excelcell.setCellStyle(style);
}
FileOutputStream fileout=new FileOutputStream(fname);
Excelworkbook.write(fileout);
fileout.flush();
fileout.close();
}catch(Exception e){throw e;}
}
}
def path="D:\\Testing softwares\\Soaup UI Training\\data.xlsx"
ob=new readxl(path)
log.info ob.getLastrow("Sheet1")
log.info ob.getCelldata(1,1)
log.info ob.getCelldata(1,2)
ob.setCelldata(path,"pass",1,3)
11. Reading Database
import groovy.sql.Sql
//obtain the database
//do the transaction
try{
//connecting the database
def dbURL="jdbc:mysql://localhost:3306/test"
def dbUsername="root"
def dbPassword=""
def dbDriver="com.mysql.jdbc.Driver"
def db= Sql.newInstance(dbURL,dbUsername,dbPassword,dbDriver)
//inserting values into table
//db.execute('insert into product values(3,7,"test",450,2)')
//delete the row from table
db.execute('delete from product where prod_name="test"')
//interacting with database
/************************Select Query******************/
def q1="select * from table1" //simple select query
def q2="select * from table1 where prod_id='2'"
def q3="select * from table1 where prod_name like '%SOAP%'"
//parameterization
def x='Story Book'
def q4="select * from product where prod_name = $x"
def insert="insert into table1 select 3,6,book,200,78"
//eachRow, rows
db.eachRow(q4){
log.info "${it.prod_name}"+"="+"${it.prod_price}"
//columnn indexes
log.info it[0]+"-----------"+ it[1]
}
}catch(Exception e){
}finally{
//closing the database
db.close()
1.To Print anything:
log.info "hello"
def x="Myname"
log.info x
log.info "Starting the test"
log.error "An error has occured while execution"
log.info "ending the test"
2.Setting the properties at different levels:
project Level:
testRunner.testCase.testSuite.project.setPropertyValue("projectproperty","projectpropertyvalue")
Test Suite level:
testRunner.testCase.testSuite.setPropertyValue("suiteproperty","suitepropertyvalue")
Test Case Level:
testRunner.testCase.setPropertyValue("testcaseproperty","propertyvalue")
Global level:
com.eviware.soaupui.SoapUi.getGloabalProperties.setGloabalProperyValue("globalproperty","gloabalpropertyvalue")
3.Retrieve the properties at different levels:
project Level:
testRunner.testCase.testSuite.project.getPropertyValue("projectproperty")
Test Suite level:
testRunner.testCase.testSuite.getPropertyValue("suiteproperty")
Test Case Level:
testRunner.testCase.getPropertyValue("testcaseproperty")
Global level:
com.eviware.soaupui.SoapUi.getGloabalProperties.setGloabalProperyValue("globalproperty")
4. Print the project,testsuite,testcase and test Step Name:
log.info testRunner.testCase.testSuite.project.name
log.info testRunner.testCase.testSuite.name
log.info testRunner.testCase.name
log.info context.getCurrentStep().name
5. Change the requestXml from groovy
def groovyutils=new com.eviware.soapui.support.GroovyUtils(context)
def holder= groovyutils.getXmlHolder("allplayersrequest#request)
holder["//foot:bselected"]="wales"
holder.updateProperty()
context.requestContext=holder.xml
6. Run a testcase located in another project
1st Way:
def prj=testRunner.testCase.testSuite.project.workspace.getProjectName("Module1")
tcase=prj.testSuites['TestSuite1'].testCases['TestCase1']
tstep=tcase.getTestStepByName("allplayersrequest")
def runner=tstep.run(testRunner,context)
log.info("runner Status.......:"+ runner.hasResponse())
7. Accessing property files
Properties prop=new Properties()
String path=System.getPorperty("user.dir") //this will give the path till bin dir of soapUI folder
def propfile= path +"\\test.properties"
FileInputStream fis=new FileInputStream(propfile)
prop.load(fis)
log.info prop.getProperty("Name")
log.info prop.getProperty("Address")
log.info prop.getProperty("Phone")
Note: property file should be in bin folder of souapui folder
property file looks something as below
Name=xyz
Address=address
Phone=00000
8. Accessing csv file
1st Method
import java.io.file
import java.io.FileNotFoundException
import java.util.Scanner
path=<<csv file path>>
File file=new File(path)
Scanner inputstream=new Scanner(file)
try
{
inputsteam.next()
while(inputstream.hasnext())
{
String d=inputstream.next()
log.info d
}
inputstream.close()
}catch(FileNotFoundException e){e.printStackTrace()}
2nd Method
def path=<<path of csv file>>
context.filereader=new BufferedReader(new FileReader(path))
File f=new File(path)
List lines=f.readLines()
int rows=lines.size()
for(int cntr:0..rows-1)
{
log.info lines[cntr]
}
9. Executing groovy file through groovy script
evaluate(new File("pathof groovyfile.groovy"))
10. Reading xls file
Precondtion: Copy the following jar in lib folder of SoauUI installation.
Say for example: C:\Program Files\SmartBear\SoapUI-5.2.1\lib
1.poi-3.6-20091214
2.poi-ooxml-3.6-20091214
3. poi-ooxml-schemas-3.6-20091214
4.xmlbeans-2.3.0
(The poi versions may not be same as mentioned above. That may vary with latest version releases)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
public class readxl{
public static XSSFWorkbook Excelworkbook;
public static XSSFSheet Excelworksheet;
public static XSSFCell Excelcell;
public static XSSFRow Excelrow;
public readxl(String fname)
{
try
{
FileInputStream fip=new FileInputStream(fname);
Excelworkbook=new XSSFWorkbook(fip);
}catch(Exception e){}
}
public static int getLastrow(String sheetname)
{
try
{
Excelworksheet=Excelworkbook.getSheet(sheetname);
int row=Excelworksheet.getLastRowNum();
return row;
}catch(Exception e){return -1}
}
public static String getCelldata(int rownum,int colnum)
{
try
{
Excelcell=Excelworksheet.getRow(rownum).getCell(colnum-1);
String cellval;
if(Excelcell.getCellType()==Excelcell.CELL_TYPE_STRING)
cellval=Excelcell.getStringCellValue();
else if(Excelcell.getCellType()==Excelcell.CELL_TYPE_NUMERIC)
cellval=String.value(Excelcell.getNumericCellValue());
else
cellval=null;
return cellval;
}catch(Exception e){return "";}
}
public static void setCelldata(String fname,String result,int RowNum,int ColNum)
{
CellStyle style=Excelworkbook.createCellStyle();
if(result.equalsIgnoreCase("pass"))
{
style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
}
else if(result.equalsIngnoreCase("fail"))
{
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
}
try
{
Excelrow = Excelworksheet.getRow(RowNum);
Excelcell = Excelrow.getCell(ColNum-1,Excelrow.RETURN_BLANK_AS_NULL);
if(Excelcell==null)
{
Excelcell=Excelrow.createCell(ColNum-1);
Excelcell.setCellValue(result);
Excelcell.setCellStyle(style);
}else{
Excelcell.setCellValue(result);
Excelcell.setCellStyle(style);
}
FileOutputStream fileout=new FileOutputStream(fname);
Excelworkbook.write(fileout);
fileout.flush();
fileout.close();
}catch(Exception e){throw e;}
}
}
def path="D:\\Testing softwares\\Soaup UI Training\\data.xlsx"
ob=new readxl(path)
log.info ob.getLastrow("Sheet1")
log.info ob.getCelldata(1,1)
log.info ob.getCelldata(1,2)
ob.setCelldata(path,"pass",1,3)
11. Reading Database
import groovy.sql.Sql
//obtain the database
//do the transaction
try{
//connecting the database
def dbURL="jdbc:mysql://localhost:3306/test"
def dbUsername="root"
def dbPassword=""
def dbDriver="com.mysql.jdbc.Driver"
def db= Sql.newInstance(dbURL,dbUsername,dbPassword,dbDriver)
//inserting values into table
//db.execute('insert into product values(3,7,"test",450,2)')
//delete the row from table
db.execute('delete from product where prod_name="test"')
//interacting with database
/************************Select Query******************/
def q1="select * from table1" //simple select query
def q2="select * from table1 where prod_id='2'"
def q3="select * from table1 where prod_name like '%SOAP%'"
//parameterization
def x='Story Book'
def q4="select * from product where prod_name = $x"
def insert="insert into table1 select 3,6,book,200,78"
//eachRow, rows
db.eachRow(q4){
log.info "${it.prod_name}"+"="+"${it.prod_price}"
//columnn indexes
log.info it[0]+"-----------"+ it[1]
}
}catch(Exception e){
}finally{
//closing the database
db.close()
Comments