cancel
Showing results for 
Search instead for 
Did you mean: 

Calling custom Groovy script from Script Assertion in REST request

Highlighted
New Contributor

Calling custom Groovy script from Script Assertion in REST request

Hi All,

 

I'm new to Soap UI and Groovy and possibly this is a noob question.

I have a requirement where I want to execute a custom groovy script that will perform some comparision and logic based on parameters passed, FROM a Script Assertion in a REST request.

 

Is there any possibility to do this? I tried to add a Groovy script with my code in the Test step and tried to write a logic to try and call the script from the Script assertion of a REST request. But I'm unable to get it to work.

9 REPLIES 9
Community Hero

Re: Calling custom Groovy script from Script Assertion in REST request

The question is very generic and difficult to understand unless specifics of the issue is provided with some sample data.

You may also find previous posts to see if you can find some more ideas.

You said tried some thing. Would you like to share that?


Regards,
Rao.
Highlighted
Community Hero

Re: Calling custom Groovy script from Script Assertion in REST request

Hi @jayantjayant,

Just reiterating what Rao said to provide a little perspective from someone else that has little groovyscript experience (me!) Smiley Happy

To provide helpful diagnosis of scripting issues the scripters on the forum will nearly always need to see your code (unless your query is very basic and can be resolved with a couple of lines of code).
The scripters on this forum are always a real big help, but they need more to go on that what youve initially described, but as a quick response to your question, yes its entirely feasible to do a comparison of some of your response against something else via a script assertion.

Cheers,

Rich
if this helped answer the post, could you please mark it as 'solved'? Also if you consider whether the title of your post is relevant? Perhaps if the post is solved, it might make sense to update the Subject header field of the post to something more descriptive? This will help people when searching for problems. Ta
Highlighted
Community Manager

Re: Calling custom Groovy script from Script Assertion in REST request

Hi @jayantjayant, while you are working with nmrao and richie on this, just some words of encouragement - don't ever be afraid to sound like a noob in the Community. We are all learning and this is perfectly normal not to know something. Sharing experience is the primary goal of this forumSmiley Happy


Sonya Mihaljova
Community and Education Specialist

 Join the virtual SmartBear Connect user conference on April 27-28! Get your free virtual ticket today!
Highlighted
New Contributor

Re: Calling custom Groovy script from Script Assertion in REST request

Thanks for your response Rao,

 

I am using below groovy code as an assertion script for a test step.

 

//get the path of the project root
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def projectPath = groovyUtils.projectPath
log.info(" projectPath : "+projectPath)

//get the test suite name
def testSuiteName_appName = messageExchange.modelItem.testStep.testCase.testSuite.getName()
log.info(" testSuiteName_appName : "+testSuiteName_appName)

//get the test case name
def tcaseName_dashboardName = messageExchange.modelItem.testCase.getName()
log.info(" tcaseName_dashboardName : "+tcaseName_dashboardName)

//get the test step name
def testStepName = messageExchange.modelItem.testStep.getName()
log.info(" testStepName : "+testStepName)

if(execution_mode == "testExecution" ) {

File file = new File("/tmp/Assertion_Files/"+testSuiteName_appName+"/"+tcaseName_dashboardName+"/"+testStepName+".txt")
BufferedReader br = new BufferedReader(new FileReader(file));
String fileStatement;
def newString = "";
while ((fileStatement = br.readLine()) != null) {
newString = newString + fileStatement.toString();
}

def expected_data_in_file = newString.trim().replace(' ', '');
expected_data_in_file = expected_data_in_file.replace("\n", "").replace("\r", "");

def splunkRestApiResponse = context.response.toString().trim().replace(' ', '');
splunkRestApiResponse = splunkRestApiResponse.replace("\n", "").replace("\r", "");

log.info(" splunkRestApiResponse "+splunkRestApiResponse);
log.info(" fileResponse trimmed "+expected_data_in_file) ;

assert(splunkRestApiResponse.equals(expected_data_in_file));
log.info(" Assertion Passed ") ;
}

 

It is working fine. As this is a generic code and all of my teststeps have same groovy assertion script. Is there a way to put this script at one place and then call it from each assertion script. This will help me to reduce my effort whenever there is a change in groovy script.

 

Highlighted
Community Hero

Re: Calling custom Groovy script from Script Assertion in REST request

Hi @jayantjayant,

I think i remember @Radford sets up libraries and stuff like that so he might be able to suggest some options.

Ive got a possiblity but i dont know if it is feasible. You "might" be able to add an event handler to do ehat you need, maybe TestRunListener.afterStep option with your script and using the 'Target' column in the events window to target specific test steps (give the teststeps in each testcase that need the assertion identical names....then you add in this teststep name into the Target column).

That way youd only need to add your code into the event handler editable field once and you wouldnt need to add it anywhere else.

Youd have to change your code slightly cos i think the events uses testRunner rather than messageExchange (script assertions dont have access to testRunner which is why youre using messageExchange instead).

The only problem i can foresee with this is reporting the assertion failure. I dont know how this would/could work, but i thought id mention this option just in case it can be done with a little effort. Id be interested to see if it would work myself.

Nice one,

Rich
if this helped answer the post, could you please mark it as 'solved'? Also if you consider whether the title of your post is relevant? Perhaps if the post is solved, it might make sense to update the Subject header field of the post to something more descriptive? This will help people when searching for problems. Ta
Highlighted
Community Hero

Re: Calling custom Groovy script from Script Assertion in REST request

It is definitely possible @jayantjayant 

 

There are two approaches.

1. ReadyAPI supports scripts libary where user can create classes for common tasks and re-use them whereever needed. The tool takes care of changes in the classes and compile and reload them and this does not require tool to be restarted.

See below documentation for more details.

https://support.smartbear.com/readyapi/docs/testing/scripts/library.html

 

2. For open source, there is no script library available However, similarity is that user creating the classes as above.  The difference is that if there are any changes in the class, user have to take care of compiling, creating jar, replace the jar to SOAPUI_HOME/bin/ext directory. Most importantly, tool needs a restart.

 

Our community expert@rupert_anderson created a blog with step by step procedure for the same. Please refer below:

http://rupertanderson.com/blog/1-how-to-develop-add-and-use-a-custom-groovy-library-in-soapui/

 

Either of the cases, one has to convert the current script into class / method so that it can be reused.



Regards,
Rao.
Highlighted
Community Hero

Re: Calling custom Groovy script from Script Assertion in REST request

Event handling is not suitable here.

 - assertions have different purpose that's why they are there

 - assertion vary from step to step, may not all step need the same assertions

 - assertions allows to execute them on need basis

 - since event is fired all the time, it tries to execute the code even though it is not needed

 - And @richie pointed well that "i can foresee with this is reporting the assertion failure" - is classic example for unfit to use event handling.



Regards,
Rao.
Highlighted
Community Hero

Re: Calling custom Groovy script from Script Assertion in REST request

@jayantjayant 

Just tried converting it into class / methods to achieve the same (equivalent of your script assertion)

The work is divided into two parts.

1. logging various details

2. comparing the response with a file

 

Hence, two methods created. and call the same in the script assertion.

 

So configure your script library as shown in the previous reply's  documentation link.

 

And here comes the script assertion part.

 

//optional if you want to show the log statements
Utility.showTestDetails(context, log)

//Replace the filepath absolute path; this compares current test step response with given absolute file 
assert Utility.compare(context.response, '/file/path'), 'error message comparison failure'

 

If you don't want to trim new lines, then use as below to compare

//Pass 3rd optional argugemtn value as false; 
assert Utility.compare(context.response, '/file/path', false), 'error message comparison failure'

 

And here is the Utility class

 

class Utility {	
	static def sanitize = { text -> text.trim().replace('\n', '').replace('\r', '') }
	static def showTestDetails(context, log) {
		log.with{
			 info "Project Path :  ${context.testCase.testSuite.project.path}"
			 info "Suite  : ${context.testCase.testSuite.name}"
			 info "Case  : ${context.testCase.name}"
			 info "Step  : ${context.currentStep.name}"
		}		
	}

	static def compare(response, fileName, isReplaceNewLine = true) {
		def fileContent = new File(fileName).text
		if (isReplaceNewLine) {
			sanitize(response) ==  sanitize(fileContent)
		} else {
			ressponse == fileContent
		}
	}
}

 



Regards,
Rao.
Highlighted
Community Manager

Re: Calling custom Groovy script from Script Assertion in REST request

Thanks for such great assistance, Rao, Richie!

@jayantjayant, do the suggestions given here help you resolve the issue?

---------
Tanya Gorbunova
SmartBear Community Manager

 Join the virtual SmartBear Connect user conference on April 27-28! Get your free virtual ticket today!