Thursday, February 23, 2012

Groovy Code Info






http://www.soapui.org/forum/viewtopic.php?f=2&t=6812

http://petrichoronthebreeze.blogspot.com/2012/01/soapui-logging-request-and-response-to.html

 


raw request============================

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

def d = new Date()

newdate = d.format("yyyy-MM-dd'T'HH-mm-ss") 

def myOutFile = "c:\\QA\\" + newdate + ".xml"

def f = new File(myOutFile) 

f.write("STARTING LOG...\n\n", "UTF-8") 

def rawRequest = new String( messageExchange.getRawRequestData() )

f.append("\n\n\n[INFO] RAW Request Data: " + rawRequest) 

/*context.currentStep.properties.each

{ key, value ->   f.append("${key} : ${value.value}\n") }*/

//f.append("\n\n\n")

//def requestHeaders = messageExchange.getRequestHeaders()

//f.append("[INFO] request headers: " + requestHeaders)

f.append("\n\n[INFO] response: " + messageExchange.getResponseContent() )

f.append("\n\n[INFO] time taken: " + messageExchange.timeTaken) 

assert messageExchange.timeTaken < 10000



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_EM3_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.bbc.co.uk/em3/1.0/LIB_MediaAssetService/wsdl/IMediaAssetService"

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

//holder.namespaces["se"] = "http://fabric.bbc.co.uk/em3/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.bbc.co.uk/em3/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.bbc.co.uk/em3/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 EM3 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/EM3CIV41:user=apptest;password=PASS_VALUE;

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



def query_statement = "SELECT * FROM EM3.MEDIA_ASSET where EM3.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/EM3CIV41:user=apptest;password=PASS_VALUE;

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



def query_statement = "SELECT UUID FROM EM3.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/EM3CIV41", "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 EM3.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<TESTRUNNER.TESTCASE.TESTSUITE.PROJECT.GETINTERFACECOUNT();I++)< font=""></TESTRUNNER.TESTCASE.TESTSUITE.PROJECT.GETINTERFACECOUNT();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/em3/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

}





How to create UI dialog ?

String name = UISupport.getDialogs().prompt("What is your name?", "Name prompt");

How to do log info ?
log.warn ("Am giving you warning");
log.info ("Am giving you info");
log.error("Am giving you error");






import com.eviware.soapui.SoapUIProTestCaseRunner;

import com.eviware.soapui.support.*;

import com.eviware.soapui.model.*;

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

import com.eviware.soapui.*;



public class runsoapui {



public static void main(String[] args) {

SoapUIProTestCaseRunner myrunner = new com.eviware.soapui.SoapUIProTestCaseRunner();

myrunner.setProjectFile("C:/Bskyb/soapui-project-files/PMAPI-WEB-soapui-project.xml");

myrunner.setTestSuite("webtestsuite");

myrunner.setTestCase("webtestcase");

try {

myrunner.run();

}

 catch(Exception ex)

 {

 System.out.println ("I'm here with Exception " + ex.getMessage());

 System.exit(1);

 }

}

}





// Define the path where all SQL queries are stored
String ResultSetsPath             = "PATH_TO_DIRECTORY_CONTAINING_SQL_FILES"
String ResultSetTemplateStepName  = "ResultStepTemplate"

// Try to get the template JDBC TestStep
def ResultSetTemplateStep = testRunner.testCase.getTestStepByName(ResultSetTemplateStepName)
// Make sure it's a valid JDBC TestStep
assert ResultSetTemplateStep != null
assert ResultSetTemplateStep.getClass().name.contains("JdbcRequestTestStep")

// Delete every JDBC TestStep in the current TestCase except the template steps
int TestStepCount = testRunner.testCase.getTestStepCount()
def TestStepsToDelete = []
for (int i = 0; i < TestStepCount; i++)
{
   // Get the current TestStep
   def curTestStep = testRunner.testCase.getTestStepAt(i)

   // Only delete JDBC steps
   if (!curTestStep.getClass().name.contains("JdbcRequestTestStep"))
      continue

   // Don't delete template JDBC steps
   if (curTestStep.name == ResultSetTemplateStepName || curTestStep.name.toLowerCase().contains("template"))
      continue

   TestStepsToDelete.add(i)
}
int TestStepsToDeleteCount = TestStepsToDelete.size
for (int i = TestStepsToDeleteCount - 1; i >= 0; i--)
   testRunner.testCase.removeTestStep(testRunner.testCase.getTestStepAt(TestStepsToDelete[i]))

//
// For every SQL file in the provided ResultStepsPath, clone the template TestStep with the filename as TestStep name
//
// Because of a bug in the Clone methods, we have to:
// - Create a temporary TestCase
// - Clone the original TestStep(s) to the new TestCase
// - Change the name of the the cloned TestStep(s)
// - Clone the renamed TestStep(s) to the original TestCase
// - Remove the temporary TestCase
def tmpCloneTestCase = testRunner.testCase.testSuite.addNewTestCase("TemporaryCloneTestCase")
new File(ResultSetsPath).eachFile
{
   // Ignore files that do not end in .sql
   if (it.name.endsWith(".sql"))
   {
      // Make sure we can read the file
      assert it.canRead()

      // Get the new name for the testStep
      String newStepName = it.name[0..-5]

      // Clone the template TestStep
      def newStep = ResultSetTemplateStep.clone(tmpCloneTestCase, newStepName)
      newStep.setName(newStepName)
    
      // Update the query of the TestStep with the contents of the file
      newStep.setQuery(it.text)

      // Now clone the temporary testStep to the original testCase
      newStep.clone(testRunner.testCase, newStepName)

      // Remove the temporary testStep
      tmpCloneTestCase.removeTestStep(newStep)
   }
}
testRunner.testCase.testSuite.removeTestCase(tmpCloneTestCase)

// Save the project
assert testRunner.testCase.testSuite.project.save() == true







//
// For every SQL file in the provided ResultStepsPath, clone the template TestStep with the filename as TestStep name
def tmpCloneTestCase = testRunner.testCase.testSuite.addNewTestCase("TemporaryCloneTestCase")
new File(ResultSetsPath).eachFile
{
   // Ignore files that do not end in .sql
   if (it.name.endsWith(".sql"))
   {
      // Make sure we can read the file
      assert it.canRead()

      // Get the new name for the testStep
      String newStepName = it.name[0..-5]

      // Clone the template TestStep
      def newStep = ResultSetTemplateStep.clone(tmpCloneTestCase, newStepName)
      newStep.setName(newStepName)
    
      // Update the query of the TestStep with the contents of the file
      newStep.setQuery(it.text)

      // Now clone the temporary testStep to the original testCase
      newStep.clone(testRunner.testCase, newStepName)

      // Remove the temporary testStep
      tmpCloneTestCase.removeTestStep(newStep)
   }
}
testRunner.testCase.testSuite.removeTestCase(tmpCloneTestCase)

// Save the project
assert testRunner.testCase.testSuite.project.save() == true



/////////




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

def headers = new StringToStringMap()
headers.put("param","value")
testRunner.testCase.getTestStepByName("REST Test Request").testRequest.setRequestHeaders(headers)





import com.eviware.soapui.impl.wsdl.teststeps.*
import com.eviware.soapui.support.types.StringToStringsMap

for( testCase in testSuite.getTestCaseList() ) {
   for( testStep in testCase.getTestStepList() ) {
      if( testStep instanceof WsdlTestRequestStep ) {
         def headers = new StringToStringsMap()
         headers.put(testSuite.getPropertyValue("ExampleHeaderName"),testSuite.getPropertyValue("ExampleHeaderValue"))

         log.info("Setting HTTP headers ${headers} in test case ${testCase.getLabel()}")
         testStep.getTestRequest().setRequestHeaders(headers)
      }
   }
}











1. Accessing Properties, Settings and Names


1.1. Get and Set properties


Getting properties from groovy is straight-forward; all objects that contain properties have a getPropertyValue / setPropertyValue methods. The following examples are from inside a Groovy Script step:


01.// get properties from testCase, testSuite and project

02.def testCaseProperty = testRunner.testCase.getPropertyValue( "MyProp" )

03.def testSuiteProperty = testRunner.testCase.testSuite.getPropertyValue( "MyProp" )

04.def projectProperty = testRunner.testCase.testSuite.project.getPropertyValue( "MyProp" )

05.def globalProperty = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "MyProp" )

06.  

07.// setting values is equally straigh forward

08.testRunner.testCase.setPropertyValue( "MyProp", someValue )

09.testRunner.testCase.testSuite.setPropertyValue( "MyProp", someValue )

10.testRunner.testCase.testSuite.project.setPropertyValue( "MyProp", someValue ) 

11.com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( "MyProp", someValue )

From inside a Script Assertion, you have to access testCase in another way:


1.def testCaseProperty = messageExchange.modelItem.testStep.testCase.getPropertyValue( "MyProp" )

Have a look at the TestPropertyHolder interface for digging into the object model.

1.2. Get and Set Settings


Global preferences can be set via the SoapUI.settings property, the different tabs have corresponding Settings interfaces in the com.eviware.soapui.settings package, each interface defines constants for each settings. So for example to set the SSL Keystore and password programmatically, you could call


01.import com.eviware.soapui.settings.SSLSettings

02.import com.eviware.soapui.SoapUI 

03.  

04.// set

05.SoapUI.settings.setString( SSLSettings.KEYSTORE, pathToKeystore )

06.SoapUI.settings.setString( SSLSettings.KEYSTORE_PASSWORD, keystorePassword )

07.  

08.// get

09.SoapUI.settings.getString( SSLSettings.KEYSTORE, "value to return if there is no such setting set" )

1.3. Project name


This is how to access the Project name from a Groovy Script TestStep:


1.testRunner.testCase.testSuite.project.name

(almost all items have a name property)

2. DataSources and DataSinks


2.1. Implementing Groovy DataSources and DataSinks


Here's an example Groovy DataSource to get you going:


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

02.def projectPath = groovyUtils.projectPath

03.def folderName = projectPath + "/testData"

04.def row = testRunner.testCase.testSteps["DataSource"].currentRow

05.def allFiles = []

06.new File( folderName ).eachFile() { file ->

07.   if( file.name =~ /.txt/ )

08.   {

09.      allFiles.add( file.name )  }

10.   }

11.  

12.if ( (row + 1) <= allFiles.size )

13.{

14.   // output to the TestStep property called inputData

15.   result["inputData"] = new File( folderName + "/" + allFiles[row] ).text

16.}

Here's an example Groovy DataSink :


1.// Write the response from the "Test Request: login" TestStep to a file

2.def currentUser = context.expand( '${#TestCase#currentUser}' )

3.def response = context.expand( '${Test Request: login#Response}' )

4.new File( "C:/Users/eviware/" + currentUser + "_response.txt" ).write( response )

5.  

6.// To use another charset than the default, do this instead:

7.// new File( "C:/Users/eviware/" + currentUser + "_response.txt" ).write( response, "UTF-8" )

2.2. Aggregating multiple DataSource rows to the same request


One way to do this is to use a Datasource + Datasource Loop with a Groovy step between which appends the Datasource elements to a property, and then use the property after exiting the loop.


1.def countryCode = context.expand( '${DataSource#CountryCode}' )

2.def countryName = context.expand( '${DataSource#CountryName}' )

3.  

4.def frag = context.expand( '${Properties#XmlFragment}' )

5.  

6.def newPropertyValue = '${frag}${countryCode}${countryName}'

7.testRunner.testCase.setPropertyValue( 'XmlFragment', newPropertyValue )

Thanks to M McDonald for this one!

2.3. Randomizing DataSource rows


There is no built in support for DataSources fetching random rows in soapUI, but this can be achieved with some scripting. Structure your TestCase like this:


The TestSteps should contain the following:

Original DataSource

A DataSource test step for the actual data that you want to randomize. Use this as you would normally.

Collect row


1.// create list if necessary

2.if( context["allRows"] == null )  context["allRows"] = []

3.  

4.// append current row from Original Source to allRows

5.context["allRows"] << context.expand( '${Original Source#output}' )

Original loop

DataSource Loop that loops to Collect row (Target Step) for each row in Original Source (DataSource Step).

Shuffle collected rows


1.Collections.shuffle( context["allRows"] )

Groovy DataSource


1.def row = testRunner.testCase.testSteps["Groovy DataSource"].currentRow

2.  

3.if ( row + 1 <= context["allRows"].size() ) 

4.{

5.    result["randomRow"] = context["allRows"][row]

6.}

Groovy DataSource loop

DataSource Loop that loops to the first test step using the random data (Target Step) for each row in Groovy DataSource (DataSource Step).

3. XML nodes


3.1. Iterate nodes


A common and equally straight forward task, use the GroovyUtils class to create an XmlHolder, which you can use for a variety of XML related activities:


1.// create groovyUtils and XmlHolder for response of Request 1 request

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

3.def holder = groovyUtils.getXmlHolder( "Request 1#Response" )

4.  

5.// loop item nodes in response message

6.for( item in holder.getNodeValues( "//item" ))

7.    log.info "Item : [$item]"

If the desired content is namespace qualified (very likely for SOAP responses), you need to define the namespace first. Continuoing from above:


1.// define namespace

2.holder.namespaces["ns"] = "http://acme.com/mynamspace"

3.  

4.// loop item nodes in response message

5.for( item in holder.getNodeValues( "//ns:item" ))

6.   log.info "Item : [$item]"

3.2. Count nodes


Use the GroovyUtils class to create an XmlHolder, which you can use for a variety of XML related activities:


1.// create groovyUtils and XmlHolder for response of Request 1 request

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

3.def holder = groovyUtils.getXmlHolder( "Request 1#Response" )

4.  

5.def numberOfLinksInParagraphs = holder["count(//html/body/p/a)"]

4. Access JMS headers


The example below sets the JMS header JMSCorrelationID to "foo4711" for myTestStep.


1.def myTestStep = testRunner.testCase.getTestStepByName("Some JMS TestStep")

2.def msgID = "foo4711"

3.  

4.myTestStep.testRequest.jMSHeaderConfig.messageSelector = "JMSCorrelationID = '${msgID}'"

5. Change a request XML from groovy


This example sets the password inside a request SOAP message:


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

02.  

03.// get XmlHolder for request message def 

04.holder = groovyUtils.getXmlHolder( "login#Request"

05.  

06.// change password using XPath 

07.holder["//username"] = "test"  

08.  

09.// write updated request back to teststep 

10.holder.updateProperty()

6. Changing response before before it gets validated


For example if you want to change all 555 to 444 in all response messages, proper way is to use RequestFilter.afterRequest event handler and add script:


01.if( request.response == null )

02.  return

03.  

04.// get response content

05.def content = context.httpResponse.responseContent

06.  

07.// manipulate content

08.content = content.replaceAll( "555", "444" )

09.  

10.// write it back 

11.context.httpResponse.responseContent = content

Now these changes will be picked up by assertions, too (read more at Custom Event Handlers).

7. Playback and MockService Control


7.1. Loop a sequence of TestSteps X times


A simple loop is easiest achieved by placing a Groovy Script TestStep after the last TestStep in the loop with the following content:


1.if( context.loopIndex == null )

2.   context.loopIndex = 0

3.  

4.if( ++context.loopIndex < 10 )

5.   testRunner.gotoStepByName( "Name of first TestStep in loop" )

This script first creates the loop counter in the context and then loops back until the value is 10 (think of it as a do...while loop)

7.2. Start and stop MockServices


This can come in handy both from the Project onLoad script (if you want to start your MockServices when the project is opened) or from a TestCase/TestSuite setup script (if you need the MockService running for your functional tests). Here from a TestCase setup script:


1.def runner = testCase.testSuite.project.mockServices["My MockService"].start()

2.context.mockRunner = runner

The returned runner object is required to stop the MockService... so save it to the context and use it in the tearDown script:


1.context.mockRunner.stop()

Have a look at the WsdlMockService and the WsdlMockRunner classes for more methods and properties that might come in handy.

8. Logging results


8.1. Saving all TestStep's results into files


To save the result (request data, response data, response time, etc.) of every executed TestStep in a Project, create a Project EventHandler (Project Window > Events tab > Add new EventHandler) of type TestRunListener.afterStep with the following content:


1.filePath = 'c:/users/henrik/soapUI-results/'

2.fos = new FileOutputStream( filePath + testStepResult.testStep.label + '.txt', true )

3.pw = new PrintWriter( fos )

4.testStepResult.writeTo( pw )

5.pw.close()

6.fos.close()

8.2. Logging the result messages of all TestSteps in all failing TestCases


This is intended to run in a TestSuite Teardown Script.


01.for ( testCaseResult in runner.results )

02.{

03.   testCaseName = testCaseResult.getTestCase().name

04.   log.info testCaseName

05.   if ( testCaseResult.getStatus().toString() == 'FAILED' )

06.   {

07.      log.info "$testCaseName has failed"

08.      for ( testStepResult in testCaseResult.getResults() )

09.      {

10.         testStepResult.messages.each() { msg -> log.info msg }

11.      }

12.   }

13.}

Thanks to Finan for this one!

9. Determine whether a TestCase is run from the Command Line, as a LoadTest, etc.



1.if( com.eviware.soapui.SoapUI.isCommandLine() )

2.{

3.   log.info "This code is executed by Command Line soapUI"

4.}

5.if( context.LoadTestContext != null )

6.{

7.   log.info "This code is executed from a LoadTest"

8.}

10. Use a JDBC Driver from inside a groovy script


If you want to do direct JDBC calls from a groovy script you first need to register the driver as follows


1.// register MySQL JDBC driver

2.com.eviware.soapui.support.GroovyUtils.registerJdbcDriver( "com.mysql.jdbc.Driver" )

(note that you still have to add the actual JDBC Driver jar to the bin\ext folder)

11. Access SOAP Operations / REST Resources


This example accesses SOAP Operations in the Sample Project.


1.import com.eviware.soapui.impl.wsdl.WsdlInterface

2.myInterface = (WsdlInterface) testRunner.testCase.testSuite.project.getInterfaceByName("SampleServiceSoapBinding")

3.myOperation = myInterface.getOperationByName("login")

4.myRequest = myOperation.getRequestByName("Request 1")







any options set to the "Run TestCase" TestStep should be applied when running the TestStep from Groovy. To run it, use the following Groovy code:

Code: Select all

def testStep = testRunner.testCase.testSteps['Run TestCase']
testStep.run( testRunner, context )

TearDown_UpdateTestLink = testRunner.testCase.testSuite.project.getTestSuiteByName("GlobalMethods").testCases["DeleteCar"];
TearDown_DeleteCar.setPropertyValue("VehicleID", 1212131);
TearDown_DeleteCar.setPropertyValue("UserName", sTestCaseName);
TearDown_DeleteCar.setPropertyValue("Password", sResult);
 
runner3 = TearDown_DeleteCar.run( new com.eviware.soapui.support.types.StringToObjectMap(), false )









while(context.expand( '${#TestCase#runningDeleteCar}' ) ){
    Thread.sleep(100)
}
testRunner.testCase.setPropertyValue("runningDeleteCar","true");
TearDown_UpdateTestLink = testRunner.testCase.testSuite.project.getTestSuiteByName("GlobalMethods").testCases["DeleteCar"];
TearDown_DeleteCar.setPropertyValue("VehicleID", 1212131);
TearDown_DeleteCar.setPropertyValue("UserName", sTestCaseName);
TearDown_DeleteCar.setPropertyValue("Password", sResult);
   
runner3 = TearDown_DeleteCar.run( new com.eviware.soapui.support.types.StringToObjectMap(), false )

testRunner.testCase.setPropertyValue("runningDeleteCar","false");







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

def d = new Date()

newdate = d.format("yyyy-MM-dd'T'HH-mm-ss") 

//def checkStep = testRunner.testCase.getTestStepByName();

def name = context.testCase.getTestStepAt(context.getCurrentStepIndex()).getLabel()



//log.info(checkStep.getLabel());

def myOutFile = "C:\\Users\\phanchat\\Desktop\\Sprint\\Sprint 13\\Result\\" + name + ".txt"

def f = new File(myOutFile) 

f.write("STARTING LOG...\n\n", "UTF-8") 

def rawRequest = new String( messageExchange.getRawRequestData() )

f.append("\n\n\n[INFO] RAW Request Data: " + rawRequest) 

/*context.currentStep.properties.each

{ key, value ->   f.append("${key} : ${value.value}\n") }*/

//f.append("\n\n\n")

//def requestHeaders = messageExchange.getRequestHeaders()

//f.append("[INFO] request headers: " + requestHeaders)

f.append("\n\n[INFO] response: " + messageExchange.getResponseContent() )

f.append("\n\n[INFO] time taken: " + messageExchange.timeTaken) 

assert messageExchange.timeTaken < 10000









groovy to read xls





import com.eviware.soapui.support.*;

import java.io.File;

import com.eviware.soapui.support.*;

import java.util.*;

import jxl.*;

import java.lang.*;

import java.io.*;

import jxl.*

import jxl.write.*

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

import com.eviware.soapui.impl.wsdl.WsdlInterface





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

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

properties.setPropertyValue( "projectPath", groovyUtils.projectPath);

String projectpath = properties.getPropertyValue("projectPath").trim();



//def currentTestSuite = testRunner.testCase.getTestSuite();

//def prj = currentTestSuite.getProject();



//log.info(prj.getInterfaceByName("m"));





java.util.List l1 = testRunner.testCase.getTestStepsOfType(com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep);

ArrayList al = l1.toArray();

String[] operationName1 = new String[al.size()+1]

Iterator itr = al.iterator();

int ii = 0;

while(itr.hasNext()) {

    com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep step = (com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep)itr.next();

    //System.out.println(step.getTestRequest());

    operationName1[ii] = step.getOperationName();

                                 log.info(operationName1[ii]);

                                 ii++;

      

}

 //operationName1[al.size()+0] = "ALL";

List<String> list = Arrays.asList(operationName1)

Set<String> set = new HashSet<String>(list)

operationName1 = new String[set.size()+1]

set.toArray(operationName1);

 operationName1[set.size()] = "ALL"; 

//String[] operationArray     = ["copyDocument","deleteDocument", "findDocumentsByExample","ALL"].toArray();

HashMap map = new HashMap();

def dialog = com.eviware.soapui.support.UISupport.createConfigurationDialog( "Select Operation to be invoke" );

dialog.addComboBox( "Operation Name", operationName1, null);

map.put( "Operation Name", properties.getPropertyValue("operationName"));



boolean finished = false;

while (!finished)  {



                if (!dialog.show(map))  {

                                testRunner.cancel( "Failed to capture entry!" );

                                return;

                }

                finished = true;

}

//String targetUrl = new String();



// get version

String operationName = (String) map.get("Operation Name");

properties.setPropertyValue( "operationName", map.get("Operation Name"));



if("ALL".equals(operationName))

{

                for(int i = 1 ; i<operationName1.length-1;i++)

                {

                                operationName = operationName1[i];  

                                properties.setPropertyValue( "operationName", operationName);

                                //log.info(operationName1.length)

                                //log.info("OPERATION NAME:::::"+operationName);

                                if(operationName != null && operationName!= "ALL" )

                                {              //testRunner.gotoStepByName("Delay");

                                                //testRunner.gotoStepByName("ALL");

                                                testRunner.runTestStepByName("ALL")

                                }

                }

}



String serviceQualorQualifiedProductRequest = null;



def serviceQualStep = testRunner.testCase.getTestStepByName(operationName);

def serviceQualStepRequest = serviceQualStep.getProperty("Request");

if( serviceQualStepRequest != null &&  serviceQualStepRequest != "")

{

serviceQualorQualifiedProductRequest  = serviceQualStepRequest.getValue();

}



//def pname = testRunner.testCase.testSuite.project.name;

//log.info(pname)

//log.info(colcount)

//if("submitApplication".equals(operationName) || "updateStatus".equals(operationName) || "addPerson".equals(operationName))

if("ALL" != operationName)

{

                                                testRunner.gotoStepByName("ALL");

                                                testRunner.runTestStepByName("ALL")

}



ALL//////////



import com.eviware.soapui.support.*;

import java.io.File;

import com.eviware.soapui.support.*;

import java.util.*;

import jxl.*;

import java.lang.*;

import java.io.*;

import jxl.*

//import jxl.write.*

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

import com.eviware.soapui.impl.wsdl.WsdlInterface

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

import com.eviware.soapui.support.types.StringToStringsMap.*;

import java.text.SimpleDateFormat

import java.text.DateFormat



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

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

properties.setPropertyValue( "projectPath", groovyUtils.projectPath);

String projectpath = properties.getPropertyValue("projectPath").trim();



String operationName = properties.getPropertyValue("operationName").trim();;

//properties.setPropertyValue( "operationName", map.get("Operation Name"));



String serviceQualorQualifiedProductRequest = null;

def serviceQualStep

def serviceQualStepRequest;

if(operationName != "ALL")

{

 serviceQualStep = testRunner.testCase.getTestStepByName(operationName);

 serviceQualStepRequest = serviceQualStep.getProperty("Request");

}



def headers = new types.StringToStringsMap()

headers.put("tenantId","831D8B107026BBEBE0400F0A32207789")

if(operationName != "ALL")

{

testRunner.testCase.getTestStepByName(operationName).testRequest.setRequestHeaders(headers)

}



if( serviceQualStepRequest != null &&  serviceQualStepRequest != "")

{

serviceQualorQualifiedProductRequest  = serviceQualStepRequest.getValue();

}



def pname = testRunner.testCase.testSuite.project.name;

log.info(pname)

//log.info(colcount)

//if("submitApplication".equals(operationName) || "updateStatus".equals(operationName) || "addPerson".equals(operationName)  )

if("ALL" != operationName)

{



Workbook workbook = Workbook.getWorkbook(new File(projectpath + "\\Data.xls"))

Sheet sheet         =  workbook.getSheet(operationName);

rowcount            =  sheet.getRows();

colcount            =  sheet.getColumns();

//log.info("row:"+rowcount)

//log.info("col:"+colcount)

//Cell a1 = sheet.getCell(0,1) // getCell(column,row) -- place some values in myfile.xls

//Cell b2 = sheet.getCell(0,0)  // then those values will be acessed using a1, b2 & c3 Cell.

//String  s1 = sheet.getCell(0,2).getContents();

//Cell c2 = sheet.getCell(1,2)

String  variableName;

String variableValue;

String testcasename;

String removeNode;

def counter=0;

while(colcount>1)

{

for(int i=1;i<rowcount;i++)

{

testcasename = sheet.getCell(counter+1,0).getContents();

variableName = sheet.getCell(0,i).getContents();

variableValue = sheet.getCell(1+counter,i).getContents();



if(variableValue == "" )

{

removeNode = variableName; 

//log.info("Remove:"+removeNode)

}

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

def holder = groovyUtils.getXmlHolder(operationName+"#Request")

holder.remove("//"+removeNode);



holder.updateProperty()

//log.info(variableName+":"+variableValue+"|")



if( variableValue.contains("/") && variableValue != null )

{

DateFormat formatter = new SimpleDateFormat("yyyy/mm/dd");

Date date = (Date)formatter.parse(variableValue);

variableValue=date.toString();

formatter = new SimpleDateFormat("yyyy-MM-DD");

variableValue=formatter.format(date);

properties.setPropertyValue(variableName,variableValue );

//log.info("DATE::"+variableName+"::"+variableValue);

}





if(variableValue!= null && variableValue!= "")

{

                properties.setPropertyValue(variableName,variableValue );

}

//log.info(s2)

}



def testStepName=operationName+"_"+testcasename



//def interfaceName="DocumentManagementSoap11";

//def operationName=operationName;

//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 );

def checkStep = testRunner.testCase.getTestStepByName(testStepName);

//log.info(checkStep.getLabel());

def newTestStepClone

if(checkStep == null)

{

               

newTestStepClone = testRunner.testCase.cloneStep(serviceQualStep,testStepName );

newTestStepClone.setDisabled(false);

}

//cloneStep(WsdlTestStep testStep, java.lang.String name)

testRunner.gotoStepByName(testStepName);

testRunner.gotoStepByName("Delay");

testRunner.runTestStepByName(testStepName)

if(newTestStepClone != null)

{

newTestStepClone.setDisabled(true);

}

//testRunner.gotoStepByName("Delay");

//testRunner.gotoStepByName(operationName);

//testRunner.runTestStepByName(operationName)

log.info(testcasename);

def aOrderStep = testRunner.testCase.getTestStepByName(operationName);

String addOrderRequest = aOrderStep.getProperty("Request").getValue();

String addOrderResponse = aOrderStep.getProperty("Response").getValue();

def d1= new File(projectpath+"//"+operationName).mkdir()

//def d1= new File(operationName).mkdir()

 //make directory, if it doesn't already exist



new File(projectpath+"//"+operationName+"//" + testcasename + "_request.xml" ).write( addOrderRequest )

new File(projectpath+"//"+operationName+"//" + testcasename + "_response.xml" ).write( addOrderResponse )



//log.info(addOrderRequest)

//log.info(addOrderResponse)

colcount--;

counter++;

serviceQualStepRequest.setValue(serviceQualorQualifiedProductRequest);

}

workbook.close()

}