cancel
Showing results for 
Search instead for 
Did you mean: 

Event handler is not triggered when running a REST test step from a Groovy step.

Contributor

Event handler is not triggered when running a REST test step from a Groovy step.

Hello, I have created a eventhandler i.e., TestRunListener.afterStep and configured to run only after REST test step. Purpose of this eventhandler is to collect some test output data such as URL, response time, execution date, HTTP Status code etc and record into a test database.

 

TestCase step up:

RESTTestStep1 (GET)

Groovy

RESTTestStep2 (POST)

 

The response from Rest TestStep 1 is consumed/parsed/built by Groovy teststep and used as a JSON payload by REST TestStep 2.  JSON payload is unique and changes based on some criteria and it needs to be iterated N number of times. In order to post these JSON payloads, I am calling REST step 2 in side groovy using  -  testRunner.runTestStepByName(RESTTestStep2)  // Execute RestStep Here //

 

Problem: Since my groovy script is calling/executing a REST test step, Event handler is not recording the result after REST step 2 is being executed. 

 

My understanding was that irrespective of calling method REST step 2 is being executed and Event handler should be triggered. But it looks like event handler treats my execution as a Groovy step not a REST step.

 

Is there any way to handle this or make this work?

 

Thanks in advance.

9 REPLIES 9
Community Hero

Re: Event handler is not triggered when running a REST test step from a Groovy step.

Please post the script that is used in Event Handler.


Regards,
Rao.
Contributor

Re: Event handler is not triggered when running a REST test step from a Groovy step.

Hi Rao, please note that below script works for all other testcases where REST  teststep is executed independently. Issue is when REST step is executed from a groovy step.

 

import net.sf.*
import net.sf.json.*
import net.sf.json.groovy.*
import groovy.sql.Sql
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder
import java.text.DateFormat
import com.eviware.soapui.model.testsuite.Assertable

 

//Get Some info
def TestSource = context.expand('${#TestSuite#TSNAME}')
def FilePath = context.expand('${#TestSuite#ResponsePath}')
def TestExec = context.expand('${#TestCase#RUNTIME}')
def TestCase = context.getTestCase().name
def TestStep = context.getCurrentStep()
def RestStepName = TestStep.getLabel()

 

def date
def URL
def ResTime
def httpStatusCode
def Response
def FileName
def DataVal


// Append TestStep name to testcase if more than one REST step is in the testcase //
if(context.getTestCase().getTestSteps().size() > 1 && TestStep.config.type == 'restrequest'){
TestCase = TestCase + ' - ' + RestStepName
}else{
TestCase = TestCase
}

 

//Perform below actions only if TestStep is a REST call //
if (TestStep.config.type == 'restrequest'){

log.info "-------------------------------------------------------"
log.info "Running ResultLogger..."

date = new Date().format("MM/dd/yyyy hh:mm a") //Get current date//
URL = context.httpMethod.getURI() //Get REST URL//
ResTime = context.httpMethod.getTimeTaken() //Get response Time//

 

// Get REST response //
try{
Response = context.expand('${'+RestStepName+'#Response}').toString()
def json = new JsonSlurper().parseText Response
Response = new JsonBuilder(json).toPrettyString()
Response = groovy.json.StringEscapeUtils.unescapeJava(Response)
}catch(e){
log.info "Exception occured while parsing"
Response = context.expand('${'+RestStepName+'#Response}').toString()

}

 

//Get Http Status Code //
try{
def httpResponseHeaders = context.testCase.testSteps[RestStepName].testRequest.response.responseHeaders
def httpStatus = httpResponseHeaders["#status#"]
httpStatusCode = (httpStatus =~ "[1-5]\\d\\d")[0]
}catch(e){
httpStatusCode = "ERROR"
}

//## Generate dynamic file name to store responses ##//
FileName = RestStepName + ".txt"
FileName = FilePath + FileName

def jsonfile = new File(FileName)
jsonfile.delete()
log.info "Writing response to $FileName"
jsonfile << Response

 

//## Capture Assertion Status ##//
def Assertion, ErrorLevel, TestStatus
try{TestStep.getAssertionList().any{
if(it.status.toString() != 'VALID'){
Assertion = 'Fail'
}else {
Assertion = 'Pass'
return
}

}

}catch(e){
log.info "Assertion script didn't run"
}

//##Get TestStatus ##//
if(httpStatusCode == '200' && Assertion == 'Pass' ){
TestStatus = 'PASS'
}else{
TestStatus = 'FAIL'
}

//## Get Error Level ##//
if(httpStatusCode != '200' && TestStatus == 'FAIL'){
ErrorLevel = 'Error at Request Level'
}else if(Assertion == 'Fail' && TestStatus == 'FAIL'){
ErrorLevel = 'Error at Assertion Level'
}else{
ErrorLevel = ''
}

 

//######################################//
//## Establish SQL Server Connection ##//
//####################################//
def sql =Sql.newInstance("jdbc:sqlserver://DATABASE_SERVER_NAME;Database=DB_Name;integratedSecurity=true","com.microsoft.sqlserver.jdbc.SQLServerDriver")
log.info "Connected to SQL server..."

//## Insert Test Results to SQL Server ##//
SQLQry = ""
SQLQry += "insert into DB_Name.DBO.TEST_RESULTs values ("
SQLQry += "'" + TestSource + "', "
SQLQry += "'" + TestCase + "', "
SQLQry += "'" + URL + "', "
SQLQry += "'" + httpStatusCode + "', "
SQLQry += "'" + ResTime + "', "
SQLQry += "'" + TestExec + "', "
SQLQry += "'" + FileName + "', "
SQLQry += "'" + TestStatus + "', "
SQLQry += "'" + ErrorLevel + "', "
SQLQry += "'" + date + "' "
SQLQry += ")"

log.info "Inserting record in SQL server..."
log.info "SQL statemement is... $SQLQry"
sql.execute SQLQry //Execute SQL statement//

log.info "Closing SQL connection..."
//## Close SQL connections ##//
sql.close() //## SQL Server Connection ##//

log.info "Finished ReportLogger..."
log.info "-------------------------------------------------------"

 

}

Community Hero

Re: Event handler is not triggered when running a REST test step from a Groovy step.

Was it a groovy script step? or script from Event handler? If not please provide the same.


Regards,
Rao.
Contributor

Re: Event handler is not triggered when running a REST test step from a Groovy step.

This is EventHandler script.

 

Groovy Step script is:

import com.eviware.soapui.support.XmlHolder
import net.sf.*
import net.sf.json.*
import net.sf.json.groovy.*
import groovy.json.JsonSlurper
import groovy.json.JsonBuilder

//## Get test step name //
def currentStepInd = context.currentStepIndex
def testStep = testRunner.testCase.getTestStepAt(currentStepInd).name
def TestStepName = testRunner.testCase.getTestStepAt(currentStepInd - 1).name
def RESTTestStep = testRunner.testCase.getTestStepAt(currentStepInd + 1).name

log.info "Running $testStep..."
log.info "------------------------------------------------"

log.info "Collect TestData from Testsuite Properties..."

def USER = context.expand('${#TestSuite#USER}')

//Parse JSON response
log.info "Parsing JSON response from $TestStepName..."
def SECNO = []
def JsonPayload
def i = 0

def response = context.expand('${'+TestStepName+'#Response}')
def json = new JsonSlurper().parseText response

json.each{
SECNO += it.SecurityNumber
JsonPayload = it
i++
}


//##Update JSON Nodes ##//
def j = 0
def jsonbuilder = new JsonBuilder(JsonPayload)

SECNO.each{
//Update JSON nodes//

jsonbuilder.content.SecurityNumber = SECNO[j]
jsonbuilder.content.UpdatedByUser = USER


//##Update TestCase Property to contain parsed json ##//
testRunner.testCase.setPropertyValue("SECNO", SECNO[j])
testRunner.testCase.setPropertyValue("JSONPayload", "${jsonbuilder}")
log.info "Updating JSON payload to TestCase property: JSONPayload"
log.info "JSON Payload is : " + context.expand('${#TestCase#JSONPayload}')
log.info "------------------------------------------------"
log.info "------------------------------------------------"
testRunner.runTestStepByName(RESTTestStep) // Execute RestStep Here //
j++
}


log.info "Finished $testStep..."
log.info "------------------------------------------------"

 

Community Hero

Re: Event handler is not triggered when running a REST test step from a Groovy step.

This is lot of code, can you precisely explain what it is intended to do?


Regards,
Rao.
Contributor

Re: Event handler is not triggered when running a REST test step from a Groovy step.

I thought my original question/post did explain that. 

 

Here is what I am doing:

Eventhandler script -  Runs after a step (actually any step). But code looks for 'restrequest' to execute big block of code. Purpose of this code is to collect stats from the rest request and record in database result table.

 

TestCase structure:

1. REST step 1 (Get some response)

2. Groovy Step

3. REST step 2 (Post data sent in jsonpayload)

 

Groovy step's purpose: 

  • Collect the response from REST Step 1
  • Collect unique Nos (SECNO) from the response and store in an array
  • Iterate to build JSONpayload and replace SECNO  in the jsonpayload during each iteration
  • Run REST step 2 with each iteration, so that json payload has unique SECNO each time

Assumption:

Eventhanlder would run after each step and when a 'REST' step is executed via groovy step, 'Big block of code' inside eventhandler would run since a REST test step was executed.

 

Issue:

'Big block of Code' in event handler is not executed after REST Step 2 is successfully executed via groovy step.

 

 

 

 

 

Contributor

Re: Event handler is not triggered when running a REST test step from a Groovy step.

@New2API @nmrao I ran into similar problem today, any help

 

Original Problem in this post is solved in latest versions of ready api but still there is 1 place from where event handler is not running, see problem statement below.

 

Problem Statement :

Create 1 event handler of type TestRunListner.afterStep in which i am doing something.

In my project there is a groovy test step which run another rest test step named as "API" via below code which does not trigger event handler.

Does Not Work

def runner = testRunner.testCase.testSuite.testCases['TS1TC1'].getTestStepByName("API")

runner.run(testRunner,context)

Works

If i have groovy script like below, event handler gets triggered.

testRunner.gotoStepByName("API")
//OR
testRunner.runTestStepByName("API")
Community Hero

Re: Event handler is not triggered when running a REST test step from a Groovy step.

What's the question?


Regards,
Rao.
Contributor

Re: Event handler is not triggered when running a REST test step from a Groovy step.

Problem Statement above is my question where TestAfter Step handler does not run when i am running step via groovy

New Here?
Join us and watch the welcome video:
Watch the new Interview
Top Kudoed Authors