Groovy Script for Regular Use

17
Context http://webservices-testing.blogspot.de/2012/04/how-to-access-project- test-suite-test.html #Project# - references a Project property #TestSuite# - references a TestSuite property in the containing TestSuite #TestCase# - references a TestCase property in the containing TestCase #MockService# - references a MockService property in the containing MockService #Global# - references a global property (optional) #System# - references a system property #Env# - references a environment variable [TestStep name]# - references a TestStep property within the current TestCase Example: def myVar = context.expand('${#TestCase#MyName}') Reading the properties from the Same level // get properties from test Case, test Suite and project def testCaseProperty = testRunner.testCase.getPropertyValue ("Country" ) log.info testCaseProperty def testSuiteProperty = testRunner.testCase.testSuite.getPropertyValue( "Country") log.info testSuiteProperty def projectProperty = testRunner.testCase.testSuite.project.getPropertyValue( "Country" ) log.info projectProperty def globalProperty = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "KPPass" ) log.info globalProperty Reading the properties from the different level def TS=testRunner.testCase.testSuite.project.testSuites["TestSuite 2"] log.info TS.getPropertyValue("name")

description

Groovy Script for Regular Use

Transcript of Groovy Script for Regular Use

Page 1: Groovy Script for Regular Use

Contexthttp://webservices-testing.blogspot.de/2012/04/how-to-access-project-test-suite-test.html

#Project# - references a Project property #TestSuite# - references a TestSuite property in the containing TestSuite #TestCase# - references a TestCase property in the containing TestCase #MockService# - references a MockService property in the containing MockService #Global# - references a global property (optional) #System# - references a system property #Env# - references a environment variable [TestStep name]# - references a TestStep property within the current TestCase

Example: def myVar = context.expand('${#TestCase#MyName}')

Reading the properties from the Same level // get properties from test Case, test Suite and project

def testCaseProperty = testRunner.testCase.getPropertyValue ("Country" ) log.info testCaseProperty

def testSuiteProperty = testRunner.testCase.testSuite.getPropertyValue( "Country") log.info testSuiteProperty

def projectProperty = testRunner.testCase.testSuite.project.getPropertyValue( "Country" ) log.info projectProperty

def globalProperty = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "KPPass" )log.info globalProperty

Reading the properties from the different level def TS=testRunner.testCase.testSuite.project.testSuites["TestSuite 2"]log.info TS.getPropertyValue("name")

def TS=testRunner.testCase.testSuite.project.testSuites["TestSuite 2"].testCases["TestCase 1"]log.info TS.getPropertyValue("name")

Updating Request Node Values at run time

Page 2: Groovy Script for Regular Use

import com.eviware.soapui.support.*

request = context.expand('${allGoalKeeper#request}') def holder=new XmlHolder(request)

holder.setNodeValue("//foot:sCountryName",'Brazil') //setting node value of request holder.updateProperty()testRunner.testCase.getTestStepByName("allGoalKeeper").setPropertyValue("request",holder.getXml())

def runner=testRunner.runTestStepByName("allGoalKeeper")def status=runner.getStatus()log.info status

Executing a step at run time

import com.eviware.soapui.support.*//to get the object of readExcel Classtestsuite = testRunner.testCase.testSuite.project.testSuites["DataDriven"];testsuite.testCases["Test Case 1"].testSteps["Test Step Name"].run(testRunner, context);

To retrieve the values from the response

def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )def holder = groovyUtils.getXmlHolder("Request 1#response")//holder.declareNamespace( 'ns', 'http://www.webserviceX.NET')holder.namespaces['ns']='http://www.webserviceX.NET';

log.info holder.getNodeValue("//ns:City") // To capture single node value

for( node in holder['//ns:City'] ) // To capture multiple node valueslog.info node

Validate Response Dynamically – (Using Xpath Assertion)

Path : http://learnsoapui.wordpress.com/category/assertion-in-soapui/

<!-- expected result value should be equal to -->

${myTestStepRequestName#Request#//WeatherByCity/CityName}

To get the data entered in a Text Box in a dialog

Page 3: Groovy Script for Regular Use

http://www.soapui.org/apidocs/com/eviware/soapui/support/components/ConfigurationDialog.html#addComboBox(java.lang.String, java.lang.String)

import com.eviware.soapui.support.*import com.eviware.soapui.support.components.*

ConfigurationDialog Dialog=UISupport.createConfigurationDialog("Test")

Map values = new HashMap()values.put("Enter Name","");

Dialog.addTextField("Enter Name", "ToolTip") Dialog.show(values)var=values.get("Enter Name")

log.info var

To get the selected value from the Combo Box in a Dialog

ConfigurationDialog Dialog=UISupport.createConfigurationDialog("Test")String[] env_options=["TEST","INT","PROD"] Dialog.addComboBox("SelectENV", env_options, "Select Environment")

Map Value= new HashMap() Value.put("SelectENV","") Dialog.show(Value)var=Value.get("SelectENV")log.info var

To Capture a password

import com.eviware.soapui.support.*import com.eviware.soapui.support.components.*

char[] Password = UISupport.promptPassword("Enter Password", "Password Screen") String var=new String(Password)log.info var

Attaching a file in soapui

http://www.soapui.org/forum/viewtopic.php?t=12524http://stackoverflow.com/questions/9066049/attaching-file-in-soapui-with-groovyhttp://stackoverflow.com/questions/7482353/change-soapui-request-with-groovy

http://www.soapui.org/Functional-Testing/script-assertions.html - it has code check this

http://www.techques.com/question/1-9066049/Attaching-file-in-SoapUI-with-groovy -IMP

Page 4: Groovy Script for Regular Use

//get request def request = testRunner.testCase.getTestStepByName( "Request 1" ).testRequest // clear existing attachments for( a in request.attachments ) { request.removeAttachment( a ) } // get file to attach //def fileName = context.expand( '${Source of data#PathToXRC File data name }' ) def fileName = context.expand( '${#TestCase#XRC_file_name}' ) def filePath = context.expand( '${#TestCase#XRC_files_path}' ) log.info "file: " + filePath + fileName def file = new File(filePath + fileName ) if ( file == null) { log.error "bad filename" } else { // attach and set properties def attachment = request.attachFile( file, true ) attachment.contentType = "application/octet-stream" def list = fileName.tokenize("\\"); attachment.setPart(list.last())

//def holder2 = groovyUtils.getXmlHolder( "Request 1#Request" ) // Get Request body //def startDate2 = holder2.setNodeValue( "//blac:FileByteStream","cid:"+list.last()); //Set "link" to attachment in request body //holder2.updateProperty() //and update // attachment.setPart(list.last()); //set attachment}

Verifying the response

http://www.soapui.org/Functional-Testing/script-assertions.html

The Script-Assertion allows for arbitrary validation of a message, which included message content,

HTTP headers, etc. Validation scripts are written in the project scripting language (Groovy or

JavaScript) and are executed whenever the assertion-status of the containing sampler TestStep is

updated. Add a Script Asssertion to your TestStep with the standard "Add Assertion" button;

Page 5: Groovy Script for Regular Use

which brings up the following configuration dialog

The top area is a standard soapUI script editor, with corresponding popup menu and actions. The

Run button executes the assertion script against the last received response and displays the result

in a popup window. The bottom shows the output of the log variable available in the script.

Page 6: Groovy Script for Regular Use

The messageExchange object available in the script exposes a bunch of properties related to the

last request/response messages (check out the Javadoc), lets look at some simple examples:

1. Validate the content of an HTTP Header in the response

// check for the amazon id header

assert messageExchange.responseHeaders["x-amz-id-1"] != null

Validate a certain response time

// check that response time is less than 400 ms

assert messageExchange.timeTaken < 400

Validate the existence of an attachment in the response

// check that we received 2 attachments

assert messageExchange.responseAttachments.length == 2

Validate the existence of a specific XML element in the response

// check for RequestId element in response

def holder = new XmlHolder( messageExchange.responseContentAsXml )

assert holder["//ns1:RequestId"] != null

This last example is greatly simplified in soapUI Pro which adds a corresponding wizard to the

Outline Editor;

capturing RawRequest &   Response

testCase.getTestStepByName(“myTestStep”).getProperty(“Request”).getValue()

or 

context.testCase.getTestStepAt(0).getProperty(“Request”).getValue() 

or

testRunner.testCase.getTestStepAt(0).getProperty(“Request”).getValue()

one of the ways to get the raw request data

messageExchange.getRequestContent().toString()

Page 7: Groovy Script for Regular Use

Message Exchangehttp://www.soapui.org/apidocs/com/eviware/soapui/model/iface/MessageExchange.html

Method Summary

Methods 

Modifier and Type Method and Description

String getEndpoint() 

String[] getMessages() 

ModelItem getModelItem() 

Operation getOperation() 

StringToStringMap getProperties() 

String getProperty(String name) 

byte[] getRawRequestData() 

byte[] getRawResponseData() 

Attachment[] getRequestAttachments() 

Attachment[] getRequestAttachmentsForPart(String partName) 

String getRequestContent() 

String getRequestContentAsXml() 

StringToStringsMap

getRequestHeaders() 

Response getResponse() 

Attachment[] getResponseAttachments() 

Attachment[] getResponseAttachmentsForPart(String partName) 

String getResponseContent() 

String getResponseContentAsXml() 

StringToStringsMap

getResponseHeaders() 

long getTimestamp() 

long getTimeTaken() 

boolean hasRawData() 

boolean hasRequest(boolean ignoreEmpty) 

boolean hasResponse() 

boolean isDiscarded() 

SoapUI Pro / Groovy - Scripts and scripted assertions

http://automated-joseph.blogspot.de/2011/05/soapui-pro-groovy-scripts-and-scripted.html

Page 8: Groovy Script for Regular Use

Verify Elements of Each Type are Descending by Score

import com.eviware.soapui.support.XmlHolder

import java.util.*

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

def holder =

groovyUtils.getXmlHolder( messageExchange.responseContentAsXml )

def nodeCount =

holder["count(//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e)"]

def currentType, currentScore = ""

def typeList = []

def found = false

def index = 0

currentType = holder.getNodeValue(

"//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e[1]/ns1:result[1]/

ns1:type[1]" )

currentScore = holder.getNodeValue(

"//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e[1]/ns1:result[1]/

ns1:score[1]" )

typeList.add( [ currentType, currentScore ] )

nodeCount = nodeCount.toInteger()

for ( i = 2; i < nodeCount; i++ ){

  currentType = holder.getNodeValue(

"//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e[" + i +

"]/ns1:result[1]/ns1:type[1]" )

  currentScore = holder.getNodeValue(

"//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e[" + i +

"]/ns1:result[1]/ns1:score[1]" )

  typeSize = typeList.size()

  for ( y = 0; y < typeSize; y++ ){

    if ( typeList[ y ].contains( currentType ) ){

      index = y

      found = true

      break

    }

  }

  if ( found ){

    previous = typeList[ index ]

    assert previous[ 1 ] >= currentScore

Page 9: Groovy Script for Regular Use

    found = false

  }

  else

  {

    typeList.add( [ currentType, currentScore ] )

  }

}

The Universal SLA Assertion (makes managing sla assertion values a one-

stop-shop)

def sla_time_taken = messageExchange.getTimeTaken();

def sla_time = context.expand( '${#Project#sla_time}' ).toInteger();

assert sla_time_taken < sla_time;

Header Information Assertion

def headers = messageExchange.getResponseHeaders();

def map_key = context.expand( '${#Project#map_key}' );

def map_val = context.expand( '${#Project#map_val}' );

assert headers.get(map_key).toString() == map_val;

Verifying Order of Response Elements by Element Value Assertion

import com.eviware.soapui.support.XmlHolder;

def bo_host = context.expand( '${#Project#project_host}' );

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

def holder =

groovyUtils.getXmlHolder( messageExchange.responseContentAsXml );

def nodeCount =

holder["count(//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e)"];

def expectedCount = context.expand( '$

{#Project#expected_return_count}' );

Page 10: Groovy Script for Regular Use

nodeCount = nodeCount.toInteger();

assert nodeCount == expectedCount;

previousPlayCountValue = holder.getNodeValue(

"//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e[1]/ns1:result[1]/

ns1:track[1]/ns1:playcounts[1]" ).toInteger();

for( int i = 2; i <= nodeCount; ++i ){

    currentPlayCountValue = holder.getNodeValue(

"//ns1:Response[1]/ns1:search[1]/ns1:results[1]/ns1:e[$i]/ns1:result[1]/

ns1:track[1]/ns1:playcounts[1]" ).toInteger();

    assert previousPlayCountValue >= currentPlayCountValue;

    previousPlayCountValue = currentPlayCountValue;

}

Gregorian Date String Builder

def gCalendar = new GregorianCalendar();

def returnString = null;

gCalendar.timeInMillis = System.currentTimeMillis();

return gCalendar.get(Calendar.YEAR) + "-" +\

    gCalendar.get(Calendar.MONTH) + "-" + ( gCalendar.get(Calendar.DATE)

- 1 ) +\

    " " + gCalendar.get(Calendar.HOUR_OF_DAY) + ":" +

gCalendar.get(Calendar.MINUTE) +\

    ":" + gCalendar.get(Calendar.SECOND);

Random Non-Repeating IDs String Builder

def standard_count = context.expand( '$

{Properties#standard_count}' ).toInteger();

def track_range = context.expand( '$

{Properties#track_range}' ).toInteger();

def generator = new Random();

def random_int = generator.nextInt( track_range );

def random_int_string, return_string = random_int.toString();

def jump_string = "";

Page 11: Groovy Script for Regular Use

for ( i = 1; i < standard_count; i++ ) {

    if ( ! return_string.contains( jump_string ) && return_string != ""

&& random_int < track_range ) {

        return_string = return_string + ", " + jump_string;

    }

    else {

        i--;

    }

    random_int = generator.nextInt(track_range);

    jump_string = random_int.toString();

}

return return_string;

Reversing IDs String Builder

def original = context.expand( '${Properties#tracks}' );

def tokens = original.tokenize(", ");

def size = tokens.size();

def newValue = "";

newValue = tokens[ 0 ];

tokens.remove( 0 );

for ( current in tokens ) {

    if ( current != null && current != "" ) {

        newValue = newValue + ", " + current;

    }

}

return newValue;

Shuffle IDs String Builder

def original = context.expand( '${Properties#tracks}' );

def tokens = original.tokenize(", ");

def size = tokens.size() - 1;

def newValue = "";

def generator = new Random();

Page 12: Groovy Script for Regular Use

if ( size > 0 ) {

    int r = generator.nextInt(size) + 1;

    newValue = tokens[r];

    for ( i in 1..size ) {

        r = generator.nextInt(size + 1);

        newValue = newValue + ", " + tokens[r];

        tokens.remove(r);

        size = tokens.size() - 1;

    }

}

else {

    newValue = original;

}

return newValue;

Response Elements Values String Builder

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

def holder = groovyUtils.getXmlHolder( context.expand( '${Publish

Playlist#ResponseAsXml}' ));

def nodeValue = holder.getNodeValue(

"//ns1:Response[1]/ns1:warning[1]/ns1:fail_to_add[1]/ns1:e[1]/text()" );

def i = 1;

return_string = context.expand( '${Properties#blacklisted_track_ids}' );

while ( nodeValue != null ) {

    if ( ! return_string.contains( nodeValue ) ) {

        return_string = return_string + ", " + nodeValue;

    }

    i++;

    nodeValue = holder.getNodeValue(

"//ns1:Response[1]/ns1:warning[1]/ns1:fail_to_add[1]/ns1:e[" +

i.toString() + "]/text()" );

}

return return_string;

Page 13: Groovy Script for Regular Use

Random Hex String Builder

def generator = new Random();

def r = generator.nextDouble();

return Double.toHexString(r)[4..16];

Random Characters String Builder

def generator = new Random();

def count = ( context.expand( '${Search

Properties#search_string_length}' ).toInteger() );

def r = generator.nextInt( count +1 ) +1;

def token_string = Long.toString( Math.abs(generator.nextLong() ), 36);

return token_string.getAt( 1..count );

Creating a workbook and writing into a workbook

http://www.andykhan.com/jexcelapi/tutorial.html

import jxl.*

import jxl.write.*

WritableWorkbook workbook = Workbook.createWorkbook(new File('C://Test/output.xls'))

WritableSheet sheet = workbook.createSheet("Worksheet 1", 0)

//log.info(sheet1.isHidden())

Label label = new Label(0, 2, "Test data in Column A, Row 3"); //column=0=A,row=0=1

sheet.addCell(label);

Label label1 = new Label(2, 2, "Column C, Row 3");

sheet.addCell(label1);

workbook.write()

Page 14: Groovy Script for Regular Use

workbook.close()

Reading Data from a workbook

http://www.andykhan.com/jexcelapi/tutorial.html

import jxl.*;context.setProperty("countryNames", new readExcel());public class readExcel{

Workbook w=Workbook.getWorkbook(new File('C://Documents and Settings/amunaga/Desktop/Project/Project/DataBase.xls'));

//return allElements of Column//List getValues(int sheetIndex,int colIndex)List getValues(int sheetIndex,int colIndex){def mySheet=w.getSheet(sheetIndex);List name=[];def countRows=mySheet.getRows();for (def i=1;i<countRows;i++){

name[i-1]=mySheet.getCell(colIndex,i).getContents()log.info name[i-1]

}return name

}}

Rest VS SOAP

http://pradeepbishnoi.blogspot.de/2011_02_01_archive.html