About Me

My Photo
London, United Kingdom
SOA tester in London

Wednesday, November 30, 2011

SOAPUI : Groovy Snippets

test suite use WsdlProject.addNewTestSuite().

Adding a test suite to a project,

test case to test suite and

test step to test case is done by using addNew... methods

**** To get all the methods of a class **

testRunner.testCase.testSuite.project.metaClass.methods.each { log.info it }

******** To list testcase name in a testsuite and WSDL teststep name in each testcase

*****####################################*****

import com.eviware.soapui.impl.wsdl.teststeps.*

def i=0;

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof WsdlTestRequestStep ) {

log.info i++ +"Name of testcases in this suite: " +"[" +testCase.getLabel() +"]" +" Name of the WSDL step is " +testStep.getName();

}

}

}

####################################

// get request property

request1 = groovyUtils.getXmlHolder("Initiallize#Request")

def sam = request1.xml

// set request property

request5 = testRunner.testCase.getTestStepByName( "Calcxml" )

request5.getProperty("request").setValue(sam)

#################################################################################################

// to add Assertions and remove Assertions

import com.eviware.soapui.impl.wsdl.teststeps.*

def i=0;

def a = "SOAP Response"

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof WsdlTestRequestStep ) {

// log.info i++ +" Name of testcases in this suite: " +"[" +testCase.getLabel() +"]" +" Name of the WSDL step is " +testStep.getName();

testStep.addAssertion(a)

testStep.removeAssertion(testStep.getAssertionByName(a))

}

}

}

################################################################################################3

// https://st.berserkgibbons.com/MM_XYZ3_FacadeWeb/sca/Exp_IProductService_SOAP

import com.eviware.soapui.impl.wsdl.teststeps.*

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

log.info("Setting HTTP basic auth for all WSDL test requests in test case ["+

testCase.getLabel()+"]")

for( testStep in testRunner.testCase.getTestStepList() ) {

if( testStep instanceof WsdlTestRequestStep ) {

testStep.getTestRequest()

.setUsername(testSuite

.getPropertyValue("Authorization"))

testStep.getTestRequest()

.setPassword(testSuite

.getPropertyValue("HeaderValue"))

}

}

}

##############################################################################################

log.warn ("Am giving you warning");

log.info ("Am giving you info");

log.error("Am giving you error");

import org.apache.log4j.*;

//BasicConfigurator.configure();

//LogManager.rootLogger.level = Level.INFO;

public static String PATTERN = "%d{ABSOLUTE} %-5p [%c{1}] %m%n"

def simple = new PatternLayout(PATTERN)

BasicConfigurator.configure(new ConsoleAppender(simple))

log.setLevel Level.DEBUG

LogManager.rootLogger.level = Level.ALL

if (log.isDebugEnabled()) {

log.debug "debug statement for var x: " + x

}

################################################################################################

README : setup script

import groovy.sql.Sql;

def DB_prp= new Object[4]; //array to store the db properties

def results;

def DB_connection;

//Groovy open file for reading DB related properties

def target ="D:\\soapui-release-B\\properties\\DB_connection.csv"

def i=0;

def FILE_NOT_EXISTS="$target file NOT present";

File wf= new File(target);

assert wf.exists():FILE_NOT_EXISTS;

wf.eachLine{line->

results = line.tokenize("\t");

//log.info results[1];

DB_prp[i++]=results[1].trim();

}

for (item in DB_prp) {

//log.info item;

print item+" ";

}

try {

DB_connection = Sql.newInstance(DB_prp[0], DB_prp[1],DB_prp[2],DB_prp[3]);

context.setProperty("dbConn", DB_connection);

} catch (Exception e) {

//log.error "Could not establish connection to the database."

print " could not establish connection";

}

################################################################################################

README : setting property at testsuite level

testRunner.testCase.testSuite.setPropertyValue("abc",yourValue);

def propertiesStep = testRunner.testCase.getTestStepByName( "GetVoiceItem" );

assert(propertiesStep != null);

def voiceItemHolder = groovyUtils.getXmlHolder( "GetVoiceItem#Request" )

voiceItemHolder.declareNamespace("voic", "http://www.adomo.com/VoiceItem");

voiceItemHolder.setNodeValue("//voic:identifier","Hello");

voiceItemHolder.updateProperty()

################################################################################################

//log.info context.expand('${getMediaAsset#ResponseAsXML}')

def testSuite = testRunner.testCase.testSuite.project.testSuites['MediaAssetServiceTestSuite'];

for(int i=0; i)

{

// isDisabled() mehod returns boolean value (i.e true or false)

if(!testSuite.getTestCaseAt(i).isDisabled())

{

// Lists out the name of enabled testcases

log.info testSuite.getTestCaseAt(i).getName();

}

}

################################################################################################

import com.eviware.soapui.impl.wsdl.teststeps.*;

import com.eviware.soapui.support.XmlHolder;

def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );

def i=0;

def WsdlTestRequestName;

for( testStep in testRunner.testCase.getTestStepList() ) {

if( testStep instanceof WsdlTestRequestStep ) {

// log.info i++ +"Name of testcases in this suite: " +"[" +"]" +" Name of the WSDL step is " +testStep.getName();

WsdlTestRequestName=testStep.getName();

}

}

def responseHolder = groovyUtils.getXmlHolder("${WsdlTestRequestName}#Response");

//responseHolder.declareNamespace( 'se', 'http://WEBSITE_FOR_NAME_SPACE')

responseHolder.namespaces["se"] = "http://fabric.XYZ.co.uk/XYZ3/1.0/LIB_MediaAssetService/wsdl/IMediaAssetService"

//MA_UUID=responseHolder.getNodeValue("//se:firstnodee[1]/nodenode[1]/whichnodeIwant[1]");

//holder.namespaces["se"] = "http://fabric.XYZ.co.uk/XYZ3/1.0/LIB_MediaAssetService/wsdl/IMediaAssetService"

def node = responseHolder.getNodeValue( "//se:getMediaAssetResponse[1]/getMediaAssetResponse[1]/mediaAssetInfo[1]/text[1]/UUID[1]" )

assert node != null

log.info node

log.info responseHolder.getPrettyXml();

#########################################################################################333

import com.eviware.soapui.support.XmlHolder

def holder = new XmlHolder( messageExchange.responseContentAsXml )

holder.namespaces["se"] = "http://fabric.XYZ.co.uk/XYZ3/1.0/LIB_MediaAssetService/wsdl/IMediaAssetService"

def nodeCount = holder.getDomNodes("//se:getMediaAssetResponse/getMediaAssetResponse").length

log.info nodeCount

for (def nodeIndex = 1; nodeIndex <= nodeCount; nodeIndex++) {

def node = holder.getDomNodes("//se:getMediaAssetResponse/getMediaAssetResponse/mediaAssetInfo/text/*")

node.each {

log.info "map node " + nodeIndex + " - " + it.QName.toString() + ": " + it.firstChild.nodeValue

}

}

###########################

import org.apache.log4j.*;

//BasicConfigurator.configure();

//LogManager.rootLogger.level = Level.INFO;

def PATTERN = "%d{ABSOLUTE} %-5p [%c{1}] %m%n"

def x=42;

def simple = new PatternLayout(PATTERN)

BasicConfigurator.configure(new ConsoleAppender(simple))

log.setLevel Level.DEBUG

//LogManager.rootLogger.level = Level.ALL

if (log.isDebugEnabled()) {

,    log.debug "debug statement for var x: " + x

}

log.setLevel Level.INFO

if (log.isInfoEnabled()) {

log.info "debug statement for var x: " + x

}

#########################################################################

import com.eviware.soapui.SoapUI;

import com.eviware.soapui.model.testsuite.TestRunContext;

import com.eviware.soapui.model.testsuite.TestRunner;

import com.eviware.soapui.model.testsuite.TestRunner.Status

import com.eviware.soapui.model.testsuite.TestStepResult;

def testcase = testRunner.getTestCase();

def steplist = testcase.getTestStepList() ;

def a3 = steplist[3];

def a4 = steplist[4];

def teststatus = testRunner.getStatus();

//

def step_a = "\n";

def i = 0;

for( r in testRunner.results )

{ i++;

step_a = step_a + i + " - '" + r.testStep.name + "' finished with status " + r.status + "\n" ;

}

// check the status property of the TestStepResult object created for the execution of the corresponding TestStep, available from testRunner.results array

// list possible status values : def step_a3 = com.eviware.soapui.model.testsuite.TestStepResult.TestStepStatus.values();

def P1 = testRunner.testCase.getTestStepByName( "Properties" );

com.eviware.soapui.support.UISupport.showInfoMessage(

"Run testcase = " + testcase.name + "\n"

+ "Functional steps = " + a3.name + " + " + a4.name + "\n"

+ " --> " + "Testcase run status = " + teststatus + "\n"

+ "Test steps run status : " + step_a + "\n" +

"Run parameters : Env= " + P1.getPropertyValue( "testenv" ) + "\n"

}

##################################################################################333

def testRequest = testRunner.testCase.testSteps["Request 1"].testRequest

def out = new FileWriter( "out.txt" )

out.println( testRequest.requestContent )

out.println( testRequest.response.contentAsString )

##################################################################################

// Compare testcase property and XML response property

//gp.callme(log);

/*def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);

def responseHolder = groovyUtils.getXmlHolder("getMediaAsset#Response");

responseHolder.namespaces["se"] = "http://fabric.XYZ.co.uk/XYZ3/1.0/LIB_MediaAssetService/wsdl/IMediaAssetService"

for ( value in responseHolder.getNodeValues("//se:getMediaAssetResponse/getMediaAssetResponse/mediaAssetInfo/text/*"))

{

//log.info "from response:"+value

for(prp in testRunner.testCase.getPropertyNames())

{

if(value == testRunner.testCase.getPropertyValue(prp)){

log.info "Property matches " + value +"=="+testRunner.testCase.getPropertyValue(prp);

//    log.info "Testproperty:" + testRunner.testCase.getPropertyValue(prp)

MATCHES = "True";

break;   

}

}

}

assert MATCHES == "True"*/

########################################################################################

Add new test request to testcase

import com.eviware.soapui.config.TestStepConfig;

import com.eviware.soapui.impl.wsdl.teststeps.*;

import com.eviware.soapui.impl.wsdl.*;

import com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepFactory

def testStepName="request_" + "create_customer_1"

def interfaceName="Exp_MediaAssetService_SOAP_IMediaAssetServiceHttpBinding";

def operationName="createMediaAsset";

def op = testRunner.testCase.testSuite.project.interfaces[interfaceName].operations[operationName];

def config = com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestRequestStepFactory.createConfig( op, testStepName );

def newTestStep = testRunner.testCase.addTestStep( config );

###########################################################################3

README : Add WSDL test Steps for all operations

import com.eviware.soapui.config.TestStepConfig;

import com.eviware.soapui.impl.wsdl.teststeps.*;

import com.eviware.soapui.impl.wsdl.testcase.*;

import com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepFactory

def interfaceName

def testStepName

def op

def config

def newTestStep

interfaceName= testRunner.testCase.testSuite.project.getInterfaceAt(0).getName();

for ( operationName in testRunner.testCase.testSuite.project.getInterfaceAt(0).getOperationList() ) {

testStepName="request_" + operationName.getName()

op = testRunner.testCase.testSuite.project.interfaces[interfaceName].operations[operationName.getName()];

config = com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestRequestStepFactory.createConfig( op, testStepName );

newTestStep = testRunner.testCase.addTestStep( config );

}

############################################################################\

import com.eviware.soapui.config.TestStepConfig;

import com.eviware.soapui.impl.wsdl.teststeps.*;

import com.eviware.soapui.impl.wsdl.*;

import com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepFactory

def testStepName="request_" + "create_customer_1"

def interfaceName

interfaceName= testRunner.testCase.testSuite.project.getInterfaceAt(0).getName();

def operationName="createMediaAsset";

def op = testRunner.testCase.testSuite.project.interfaces[interfaceName].operations[operationName];

def config = com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestRequestStepFactory.createConfig( op, testStepName );

def newtcase = testRunner.testCase.testSuite.addNewTestCase("Trail Name")

def newTestStep = newtcase.addTestStep( config );

##############################################################################3

README : Add datasource step of type .csv and also set start row end row

testRunner.testCase.testSteps["DataSource"].modelItem.dataSource = "File"

testRunner.testCase.getTestStepByName("DataSource").getDataSource().setFileName("C:/Temp/366.xml")

testRunner.testCase.testSteps["DataSource"].setEndRow("6");

testRunner.testCase.testSteps["DataSource"].setStartRow("5");

log.info testRunner.testCase.testSteps["DataSource"].getStartRow();

log.info testRunner.testCase.testSteps["DataSource"].getEndRow()

############################################################################

Get headers from CVS file and add to datasource as property

testRunner.testCase.

//csv file containing data

String strFile = "D:\\Systest\\B\\testdata\\create_asset.csv";

//create BufferedReader to read csv file

BufferedReader br = new BufferedReader( new FileReader(strFile));

String strLine = "";

StringTokenizer st = null;

int lineNumber = 0, tokenNumber = 0;

//read comma separated file line by line

while( (strLine = br.readLine()) != null)

{

lineNumber++;

//break comma separated line using ","

st = new StringTokenizer(strLine, ",");

while(st.hasMoreTokens())

{

//display csv values

tokenNumber++;

testRunner.testCase.testSteps["DataSource"].addProperty(st.nextToken());

//log.info("Line " + lineNumber +", Token " + tokenNumber+ ", Token : "+ st.nextToken());

}

break;

//reset token number

tokenNumber = 0;

}

############################################################################\

README: Replace testStep name as testcase name

import com.eviware.soapui.impl.wsdl.teststeps.*

def i=0;

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof WsdlTestRequestStep ) {

def tcasename=testCase.getLabel()

def tstepname=tcasename.replaceAll("TestCase","TestStep");

// log.info i++ +"Name of testcases in this suite: " +"[" +tcasename +"]"

// log.info " NewName of the WSDL step is " + tstepname;

testStep.setName(tstepname);

}

}

}

############################################################################\

README Add New End points.

//****************************************************************************************

/*

// Add New End points.

def endpoints=[];

def CI = "192.168.9.95:9443";

def ST = "192.168.9.95:9443";

def newendpoint;

for ( endpoint in testRunner.testCase.testSuite.project.getInterfaceAt(1).getEndpoints())

endpoints[0]=endpoint

newendpoint=endpoints[0].replace('localhost:9080','192.168.9.95:9443')

//log.info endpoints[0]

//log.info newendpoint

testRunner.testCase.testSuite.project.getInterfaceAt(0).addEndpoint(newendpoint);

for ( endpoint in testRunner.testCase.testSuite.project.getInterfaceAt(0).getEndpoints())

log.info endpoint

*/

//*****************************************************************************************

######################################################################################

//README : Command line arguments for Groovy.

for (arg in this.args) {

println arg

}

######################################################################################

//Parse CSV file

testfile = new File("D:/Release-B/ReleaseA-Enhancement/DMI XYZ3 Release B_Test Cases_Release A Enhancements.csv")

def tcaseDescription =[];

def i=0;

testfile.eachLine{

//log.info it

tcaseDetails = it.split(/,/).toList()

for (tcaseDetail in tcaseDetails)

{ log.info "Cellnumber "+ i++ + tcaseDetail}

######################################################################################

//Parse CSV File and set Testcase description

testfile = new File("C:/test.csv")

def tcaseDescription =[];

def i=0;

testfile.eachLine{

//log.info it

tcaseDetails = it.split(/,/).toList()

tcaseDescription[i++]=tcaseDetails[5]

}

def j=0;

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

testCase.setDescription(tcaseDescription[j++]);

}

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

log.info testCase.getDescription();

}

######################################################################################

/*

// *** Replace Teststeps Name as like TestCase Name

//

import com.eviware.soapui.impl.wsdl.teststeps.*

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

def i=1;

// for( testCase in testRunner.testCase.testSuite.getTestCaseByName("ReAEn_TC.139 MediaAssetService createMediaAsset TestCase") ) {

for( testStep in testCase.getTestStepList() ) {

// if( testStep instanceof WsdlTestRequestStep ) {

def tcasename=testCase.getLabel()

def tstepname=testStep.getLabel()

tstepname=tcasename.replaceAll("TestStep 1","TestStep");

tstepname=tcasename.replaceAll("TestCase","TestStep")+i++;

// log.info i++ +"Name of testcases in this suite: " +"[" +tcasename +"]"

log.info " NewName of the WSDL step is " + tstepname;

testStep.setName(tstepname);

}

}

}

*/

/*

// ** Update Testcase Description from CSV File

//

testfile = new File("C:/test.csv")

def tcaseDescription =[];

def i=0;

testfile.eachLine{

//log.info it

tcaseDetails = it.split(/,/).toList()

tcaseDescription[i++]=tcaseDetails[5]

}

def j=0;

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

testCase.setDescription(tcaseDescription[j++]);

}

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

log.info testCase.getDescription();

}

*/

/*

// ** Add all 3 assertions to teststep

//

import com.eviware.soapui.impl.wsdl.teststeps.*;

def i=0;

def a = "SOAP Response"

def b = "Not SOAP Fault"

def c = "Schema Compliance"

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof WsdlTestRequestStep ) {

if(!testStep.getAssertionByName(a)) testStep.addAssertion(a)

if(!testStep.getAssertionByName(b)) testStep.addAssertion(b)

if(!testStep.getAssertionByName(c)) testStep.addAssertion(c)

}

}

}

*/

######################################################################################

Add datasource step programatically !

def tcase = testRunner.testCase.testSuite.getTestCaseAt(1);

log.info tcase.getLabel();

log.info " "

def newtcase = testRunner.testCase.testSuite.addNewTestCase("AAA")

def config = com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepRegistry.getInstance().getFactory("datasource").createNewTestStep(tcase,"trial");

newtcase.addTestStep( config );

tcase.addTestStep( config );

######################################################################################

Add datasource step programatically to all testcases in all testsuite

import com.eviware.soapui.impl.wsdl.teststeps.*;

def gi = com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepRegistry.getInstance();

def gf = gi.getFactory("datasource");

def datasourcename;

def config

for (testsuite in testRunner.testCase.testSuite.project.getTestSuiteList()){

for( testCase in testsuite.getTestCaseList() ) {

datasourcename = testCase.getLabel()+"_datasource";

config = gf.createNewTestStep(testCase,datasourcename);

testCase.addTestStep( config );

}

// log.info testsuite.getLabel();

}

for (testsuite in testRunner.testCase.testSuite.project.getTestSuiteList()){

for( testCase in testsuite.getTestCaseList() ) {

datasourcename = testCase.getLabel()+"_datasource";

testCase.getTestStepByName(datasourcename).modelItem.dataSource = "File"

// log.info testCase.getTestStepByName(datasourcename);

testCase.getTestStepByName(datasourcename).getDataSource().setFileName("C:/Temp/366.xml")

testCase.testSteps[datasourcename].setEndRow("6");

testCase.testSteps[datasourcename].setStartRow("5");

}

}

######################################################################################

def newtcase = testRunner.testCase.testSuite.addNewTestCase("AAA")

def config = com.eviware.soapui.impl.wsdl.teststeps.registry.WsdlTestStepRegistry.getInstance().getFactory("jdbc").createNewTestStep(newtcase,"trial");

newtcase.addTestStep( config );

######################################################################################

def groovyUtils = new com.eviware.soapui.support.GroovyUtilsPro( context );

holder = groovyUtils.getXmlHolder( context.expand( '${JDBC Request#ResponseAsXML}' ) );

quota = holder.getNodeValue("//Results[1]/ResultSet[1]/Row[1]//PRODUCT.ID[1]/text()");

for ( value in holder.getNodeValues("//Results[1]/ResultSet[1]/Row[1]//*"))

log.info value

######################################################################################

//Change Datasource file path to whatever you want :)

import com.eviware.soapui.impl.wsdl.teststeps.*

for (testsuite in testRunner.testCase.testSuite.project.getTestSuiteList()){

for( testCase in testsuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof WsdlDataSourceTestStep ) {

testCase.getTestStepByName(testStep.getLabel()).getDataSource().setFileName("C:/Temp/366.xml")

}

}

}

}

######################################################################3

//Tip to generate a random element from an array

a = [1,2,3,4,5,6,7,8,9]

random = new Random()

log.info a[random.nextInt(50) % 9]

###########################################################################

// Add properties at testsuite level from a file along with a SQL query

import groovy.sql.Sql;

def MA_UUID;

def target ="D:\\soapui-release-B\\properties\\mediaasset.csv"

def i=1;

def FILE_NOT_EXISTS="$target file NOT present";

File wf= new File(target);

wf.write('')

//jdbc:db2://dmmdb4501.berserkgibbons.com:60000/XYZ3CIV41:user=apptest;password=PASS_VALUE;

def sql = Sql.newInstance("jdbc:db2://dmmdb4501.berserkgibbons.com:60000/XYZ3CIV41", "apptest","testing123", "com.ibm.db2.jcc.DB2Driver");

def query_statement = "SELECT * FROM XYZ3.MEDIA_ASSET where XYZ3.MEDIA_ASSET.STATE_ID='1' fetch first 5 rows only";

sql.eachRow(query_statement) { row ->

wf<< "deleltedmediaasset"+i+++"="+row.UUID

wf<< "\n"

}

sql.close();

log.info "Closed Database Connection. "

testRunner.testCase.testSuite.addPropertiesFromFile(target)

###############################################################################################################

// Add a properties in testcase level from a SQL query - random UUID generator

// Add properties at testcase level from a file along with a SQL query

import groovy.sql.Sql;

def MA_UUID;

def target ="D:\\soapui-release-B\\properties\\mediaasset.csv"

def i=1;

def j=0;

def FILE_NOT_EXISTS="$target file NOT present";

File wf= new File(target);

wf.write('')

def mediaassetranduuid=[];

random = new Random()

//jdbc:db2://dmmdb4501.berserkgibbons.com:60000/XYZ3CIV41:user=apptest;password=PASS_VALUE;

def sql = Sql.newInstance("jdbc:db2://dmmdb4501.berserkgibbons.com:60000/XYZ3CIV41", "apptest","testing123", "com.ibm.db2.jcc.DB2Driver");

def query_statement = "SELECT UUID FROM XYZ3.MEDIA_ASSET fetch first 50 rows only";

sql.eachRow(query_statement) { row ->

//wf<< "deleltedmediaasset"+i+++"="+row.UUID

//wf<< "\n"

mediaassetranduuid[j++]=row.UUID

}

sql.close();

def UUID=mediaassetranduuid[random.nextInt(300) % 49];

log.info UUID

testRunner.testCase.testSuite.getTestCaseByName("ReAEn_TC.043 MediaAssetService getMediaAsset TestCase").setPropertyValue("MEDIAASSET_UUID",UUID)

//wf<< "MEDIAASSET_UUID="+UUID

//log.info "MEDIAASSET_UUID="+mediaassetranduuid[random.nextInt(300) % 50]

//log.info "Closed Database Connection. "

//testRunner.testCase.testSuite.getTestCaseByName("ReAEn_TC.043 MediaAssetService getMediaAsset TestCase").removeProperty("MEDIAASSET_UUID")

##############################################################################################

//Parse CSV file - for RESTful services - compare response

def i=0;

def j=0

def k=0

def id=[];

def logicaldelete=[];

def name=[];

testfile = new File("D:/Systest/Test-Data/RefAnnotationTrackType.csv")

testfile.eachLine{

tcaseDetails = it.split(/,/).toList();

id[i++]= tcaseDetails[0];

logicaldelete[j++]= tcaseDetails[1];

name[k++]= tcaseDetails[2];

}

//-------------------------------------   

i=0;

j=0;

k=0;

//-------------------------------------

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);

def responseHolder = groovyUtils.getXmlHolder("RefAspectRatio#ResponseAsXml");

node = responseHolder.getDomNodes("//Response/e[*]/id[1]" )

node.each {

assert it.firstChild.nodeValue == id[i++]

}

node2 = responseHolder.getDomNodes("//Response/e[*]/logicalDelete[1]" )

node2.each {

assert it.firstChild.nodeValue == logicaldelete[j++]

}

node3 = responseHolder.getDomNodes("//Response/e[*]/name[1]" )

node3.each {

assert it.firstChild.nodeValue == name[k++]

}

##############################################################################################

//README : Set file name of datasource testSTep automatically..

import com.eviware.soapui.impl.wsdl.teststeps.*

def i=0;

/*

def post = context.getProperty("postMethod")

post.setRequestHeader("Test", "Hello") <-- adding header

for ( h in post.getRequestHeaders() )

log.info( h )

*/

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof ProJdbcRequestTestStep ) {

//log.info i++ +"Name of testcases in this suite: " +"[" +testCase.getLabel() +"]" +" Name of the WSDL step is " +testStep.getName();

log.info testRunner.testCase.getTestStepByName(testStep.getName()).setFileName("C:/Temp/366.xml")

}

}

}

##############################################################################################

README : Get Database connection string from Project level properties.

//def con = testSuite.project.getConfig()

//def dbcc = con.getDatabaseConnectionContainer()

//log.info dbcc.getDatabaseConnectionArray(0).getConnectionString()

##############################################################################################

setup scripts for DB connection

NOTE: You have to run as a testcase ..if you run only teststep it will fail... ok ..run testcase level.

---------------------------------

1) put this in setup script at testcase level

----------------------------------------------

import groovy.sql.Sql;

try {

def DB_connection = Sql.newInstance("jdbc:db2://dmmdb4501.berserkgibbons.com:60000/XYZ3CIV41", "apptest","testing123", "com.ibm.db2.jcc.DB2Driver");

context.setProperty("dbConn", DB_connection);

log.info "Made DB connection"

} catch (Exception e) {

log.info "Could not establish Database Connection";

}

2) Put this in Groovy step where ever you are

-----------------------------------------------

//Check if connection to database is available

if (context.dbConn)

{

//connection to the database

def sql = context.dbConn

row = sql.firstRow("SELECT * FROM XYZ3.MEDIA_ASSET fetch first 1 rows only ")

log.info row.UUID

}

else log.info "Setup failed DB not running"

##############################################################################################

Add HTTP headers to Requests

NOTE: will work only in 3.5.1 version

import com.eviware.soapui.impl.wsdl.teststeps.*

import com.eviware.soapui.support.types.StringToStringMap ;

def tc = testRunner.testCase.testSuite.getTestCaseByName("ReAEn_TC.042 MediaAssetService createMediaAsset TestCase")

def ts = tc.getTestStepByName("ReAEn_TC.042 MediaAssetService createMediaAsset TestStep1")

def ts2 =tc.getTestStepByName("r1")

def headers = new StringToStringMap()

headers.putIfMissing("Authorization","Basic VEVTVF9JJkFfU3VwZXJVc2VyOmZhYnJpYzEwMQ==")

log.info ts2.getHttpRequest().getRequestHeaders()

ts2.getHttpRequest().setRequestHeaders(headers)

log.info ts2.getHttpRequest().getRequestHeaders()

-------------------------------------------------------

import com.eviware.soapui.impl.wsdl.teststeps.*

import com.eviware.soapui.support.types.StringToStringMap ;

def headers = new StringToStringMap()

headers.putIfMissing("Authorization","Basic VEVTVF9JJkFfU3VwZXJVc2VyOmZhYnJpYzEwMQ==")

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof WsdlTestRequestStep ) {

testStep.getHttpRequest().setRequestHeaders(headers)

}

}

}

##############################################################################################

RESTful service - compare Response

import com.eviware.soapui.impl.wsdl.teststeps.*;

def teststep = testRunner.testCase.testSuite.getTestCaseByName("RefAddtnlTvMusicCode TestCase").getTestStepByName("RefAspectRatio")

teststep.addAssertion("XPath Match")

def assertion = teststep.getAssertionByName("XPath Match")

def responseAsXml = context.expand( '${RefAspectRatio#ResponseAsXml#//Response[1]}' )

//assertion.setExpectedContent(responseAsXml);

//assertion.setPath("//Response[1]");

##############################################################################################

Testcase level passing lists / properties

http://forum.eviware.com/viewtopic.php?f=2&t=4716&p=15639

##############################################################################################333

REST endpoint change

// Add New End points.

def endpoints=[];

def newendpoint;

def i=0;

for ( i=0;i

{

for ( endpoint in testRunner.testCase.testSuite.project.getInterfaceAt(i).getEndpoints() )

{

endpoints[0]=endpoint

log.info "Old end point is : " +endpoints[0]

String splitPattern = "/";

tokens = endpoints[0].split(splitPattern);

def lasttoken = tokens[tokens.length-1].toLowerCase() - "ref"

newendpoint="https://st.berserkgibbons.com/XYZ3/gateway/reference/rest/data/"+lasttoken

log.info "New endpoint is :" +newendpoint

testRunner.testCase.testSuite.project.getInterfaceAt(i).changeEndpoint(endpoints[0],newendpoint);

}

}

------------------------------------------------------------

Generate UUID - Groovy way

##############################################################

def validChars ="abcdefghijklmnopqrstuvwxyz1234567890"

j=0

String resultID = ""

int maxIndex = validChars.length()

for ( def IDlength in [8,4,4,4,12]) {

java.util.Random rnd = new java.util.Random(System.currentTimeMillis()*(new java.util.Random().nextInt()))

for ( j in 0..IDlength ) {

int rndPos = Math.abs(rnd.nextInt() % maxIndex);

resultID += validChars.charAt(rndPos)

number=resultID

}

if(IDlength!=12)

resultID = resultID+"-"

}

log.info resultID

------------------------------------------------------------

REST - Check HTTP Return Code

assert messageExchange.getResponseStatusCode() == 200

def res = messageExchange.getResponseContent()

assert res != null , 'Response must not be null'

teststeps.RestTestRequestStep

----------------------------------------------------------------

import com.eviware.soapui.impl.wsdl.teststeps.*

def ga = "Script Assertion"

String endofline = System.getProperty("line.separator");

String scripttext = "assert messageExchange.getResponseStatusCode() == 200" + endofline + "def res = messageExchange.getResponseContent()" + endofline +"assert res != null , 'Response must not be null'";

for( testCase in testRunner.testCase.testSuite.getTestCaseByName("GET_searchlocation_Stock_REST TestCase") ) {

for( testStep in testCase.getTestStepList() ) {

if (testStep instanceof RestTestRequestStep) {

if(!testStep.getAssertionByName(ga))

testStep.addAssertion(ga);

testStep.getAssertionByName("Script Assertion").setScriptText(scripttext);

testStep.getAssertionByName("Script Assertion").setName("Check HTTP Return Code");

}

}

}

----------------------------------------------------------------

Add JDBC request to all testcase

##############################################

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

testCase.addTestStep("jdbc","PreJDBC Request")

}

##############################################

import com.eviware.soapui.impl.wsdl.teststeps.*

Iterator iterator;

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof ProJdbcRequestTestStep ) {

testStep.setDriver("com.ibm.db2.jcc.DB2Driver")

}

}

}

#############################################################################

import com.eviware.soapui.impl.wsdl.teststeps.*

for( testCase in testRunner.testCase.testSuite.getTestCaseList() ) {

for( testStep in testCase.getTestStepList() ) {

if( testStep instanceof ProJdbcRequestTestStep )

{

testStep.setDbConnectionName("ST");

}

}

}

#############################################################################

def props = new java.util.Properties();

props = testRunner.testCase.getTestStepByName(“Properties”);

def propValue = props.getPropertyValue(“PropertyName”);

To access these properties in Groovy script:

def propValue = testRunner.testCase.getPropertyValue(“PropertyName”)

#######################################################################################

Send Files to FTP Location : Remember to download and place apache FTP client file in /lib/ext location

new FTPClient().with {

def media_ID = context.expand( '${DataSource_Delivery_ID#Media_ID}' )

connect host

log.info replyString

login user, password

log.info replyString

changeWorkingDirectory(remote_path);

files = listFiles(remote_path)

for (myfiles in files) {

if(myfiles.getName() =~ /Sky*/) {

log.info "Renaming : " + myfiles.getName();

rename(myfiles.getName(),media_ID);

log.info "Newfilename:" + media_ID;

}

}

disconnect();

}

########################################################################################

set DATE and time

def eventDateTime = new Date().format("yyyy-MM-dd")

def eventDateTime = new Date().format("yyyy-MM-dd'T'HH:mm:ss")

def props = new java.util.Properties();

props = testRunner.testCase.getTestStepByName("Properties");

props.setPropertyValue("filename","NEWIPTEST" + media_ID);

props.setPropertyValue("deliveryId",media_ID);

########################################################################################

To get Request and Response from PRocess instance Xpath

import com.eviware.soapui.impl.wsdl.teststeps.*;

import com.eviware.soapui.support.XmlHolder;

/* Clear log Start*/

// Karthi don't know how to do this !! :)

/* Clear log Done */

def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );

def responseHolder = groovyUtils.getXmlHolder("getCommunication#Response");

responseHolder.namespaces["axis2ns89099"] ="http://www.apache.org/ode/pmapi"

responseHolder.namespaces["ns"]="http://www.apache.org/ode/pmapi/types/2006/08/02/"

def nodeCount = responseHolder.getDomNodes("//axis2ns89099:getCommunicationResponse[1]/getCommunicationResponse[1]/ns:restoreInstance[1]/*").length

log.info nodeCount

for (def nodeIndex = 1; nodeIndex <= nodeCount; nodeIndex++) {

def node = responseHolder.getDomNodes("//axis2ns89099:getCommunicationResponse[1]/getCommunicationResponse[1]/ns:restoreInstance[1]/ns:exchange[$nodeIndex]/ns:operation[1]")

node.each {

// log.info "Node " + nodeIndex + " - " + it.QName.toString() + ": " + it.firstChild.nodeValue

// log.info "Node " + nodeIndex + " - " + it.firstChild.nodeValue

if (it.firstChild.nodeValue == "storeItem")

{

log.info "Am in storeItem"

log.info nodeIndex

def request = responseHolder.getDomNode("//ns:exchange[$nodeIndex]/ns:in[1]//*")

log.info request.toString();

def response = responseHolder.getDomNode("//ns:exchange[$nodeIndex]/ns:out[1]//*")

log.info response.toString();

}

}

########################################################################################

// How to set properties values from teststep to another testcase

import com.eviware.soapui.support.*;

def props = new java.util.Properties();

def target_prpname="CREA"

def target_testcasename="Check_Process_Status";

def prp_name = "Properties"

def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );

def holder = groovyUtils.getXmlHolder( messageExchange.responseContent );

def instanceID = holder.getNodeValue("//ns1:event[1]/ns1:sourceInstanceId[1]");

props = context.getTestCase().getTestSuite().getTestCaseByName(target_testcasename).getTestStepByName(prp_name);

props.setPropertyValue(target_prpname,instanceID)

########################################################################################

Get Endpoint WSDL URL from interface

for( inter in testRunner.testCase.testSuite.project.getInterfaces() ) {

log.info inter.getValue().getDefinition()

}

******************

//testRunner.testCase.testSuite.project.getWorkspace().createProject("Via_my_groovy", new File ("C:/Bskyb/soapui-project-files/karthi_test.xml"))

//testRunner.testCase.testSuite.project.getWorkspace().save(true)

for( inter in testRunner.testCase.testSuite.project.getInterfaces() ) {

log.info inter.getClass();

log.info inter

}

8 comments:

Rooman Ali said...

EM3... BBC :)

Bala said...

Hi Karthi,

Thanks for the wonderful effort. This would help the beginners who learn SoapUI and groovy.

I have a query.
I am having only one test request in my test case and couple of Interfaces having multiple and different operations. I need to execute the test request step by changing the interface and operations during run time.
I would really happy if you can help me to achieve this

Regards,
Bala

Prasad said...

good post Karthi...

CVN said...

Good Work Karthi,

I am novice to SoapUI and wish to use command line to run a soap request in xml file using SoapUI.

I am not getting any way to solution.

Can you pl help me in this.

Thanks in advance.

-Chittavrat

Andrew Scheel said...

Thank you for these gems. They really helped me out today!

Innovapath said...

Excellent Post. Also visit http://whiteboxqa.com/selenium.

chandrachood Penumalli said...

Hi Karthi,

It is an excellent post about SOAP UI.I do have a specific requirement which i am looking to write conditional loop assertions for my test cases.if could share your personal email i will send my requirement.if you can help that would be great.my email ID is chandrachood@gmail.com.

Thanks in advance,
Chandra

Innovapath said...

Excellent Post.Also visit http://www.whiteboxqa.com/WBQA/google/soapui_training.php