How to Capture Request and Response in testSuite TearDown using groovy - groovy

I have a testSuite with lets say 5 cases, i run the cases from my testSuite.
In my tear down script I want to capture all request and response of all testcases all test testSteps.
Below is the code I have written in tearDown TestSuite, problem in context.expand is returning empty. I assume testCase context is require, or not sure where i am going wrong.
tc_list = testSuite.getTestCaseList()
tc_count = tc_list.size()
for(i=0;i<tc_list.size();i++){
if(!tc_list[i].isDisabled()){
ts_list = tc_list[i].getTestStepList()
for(j=0;j<ts_list.size();j++){
req = testSuite.getPropertyValue("reportpath")+'/'+testSuite.getName()+'/'+tc_list[i].getName()+'/'+ts_list[j].getName()+'_RequestData.txt'
res = testSuite.getPropertyValue("reportpath")+'/'+testSuite.getName()+'/'+tc_list[i].getName()+'/'+ts_list[j].getName()+'_ResponseData.txt'
def request_expand = context.expand('${'+ts_list[j].getName()+'#Request}')
log.info '${'+ts_list[j].getName()+'#Response}'+tc_list[i].getName()
def response_expand = context.expand('${'+ts_list[j].getName()+'#Response}')
log.info response_expand
/* def req_file = new File(req)
req_file.write(request_expand,"UTF-8")
def res_file = new File(res)
res_file.write(response_expand,"UTF-8") */
}
}
}

#Ragesh kr
Whenever any time in Soap ui or Ready API you need RawRequest or RawResponse
you can just replace Request with RawRequest
and Response with RawResponse
i just did in your code and it worked
def request_expand = testSuite.getTestCaseByName(tc_list[i].getName()).getTestStepByName(ts_list[j].getName()).getPropertyValue("RawRequest")
def response_expand = testSuite.getTestCaseByName(tc_list[i].getName()).getTestStepByName(ts_list[j].getName()).getPropertyValue("RawResponse")
Some other examples to help everyone
When we just need request and response in soapui we can use below
When we just need RawRequest and RawResponse in soapui/ReadyaPI via groovy we can use below
req=context.expand('${RequestStepName#RawRequest}')
log.info req
res=context.expand('${RequestStepName#RawResponse}')
log.info res

The Below code worked for me. But I am still trying to capture rawRequest and rawResponse, which is still not achieved
tc_list = testSuite.getTestCaseList()
tc_count = tc_list.size()
for(i=0;i<tc_list.size();i++){
if(!tc_list[i].isDisabled()){
ts_list = tc_list[i].getTestStepList()
for(j=0;j<ts_list.size();j++){
req = testSuite.getPropertyValue("reportpath")+'/'+testSuite.getName()+'/'+tc_list[i].getName()+'/'+ts_list[j].getName()+'_RequestData.txt'
res = testSuite.getPropertyValue("reportpath")+'/'+testSuite.getName()+'/'+tc_list[i].getName()+'/'+ts_list[j].getName()+'_ResponseData.txt'
def request_expand = testSuite.getTestCaseByName(tc_list[i].getName()).getTestStepByName(ts_list[j].getName()).getPropertyValue("Request")
def response_expand = testSuite.getTestCaseByName(tc_list[i].getName()).getTestStepByName(ts_list[j].getName()).getPropertyValue("Response")
def req_file = new File(req)
def res_file = new File(res)
log.info testSuite.getTestCaseByName(tc_list[i].getName()).getName()+' '+testSuite.getTestCaseByName(tc_list[i].getName()).getTestStepByName(ts_list[j].getName()).getName()+' '+response_expand
if(request_expand!=null && response_expand!=null){
log.info testSuite.getTestCaseByName(tc_list[i].getName()).getName()+' '+testSuite.getTestCaseByName(tc_list[i].getName()).getTestStepByName(ts_list[j].getName()).getName()+' '+response_expand
req_file.write(request_expand,"UTF-8")
res_file.write(response_expand,"UTF-8")
}
}
}
}

Related

Asserting object count in a JSON response using groovy script

I have a question on how to assert the element_count equals to the number of objects from response.
The link to the API is https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=*******
I tried using the below code but did not have any luck trying to count the objects from the JSON response using grrovy script.
import groovy.json.JsonSlurper
def ResponseMessage = messageExchange.response.responseContent
def response = new JsonSlurper().parseText(ResponseMessage)
def elementCount = response.element_count
def idCount = response.count { it.equals('neo_reference_id') }
I was trying to count the number of neo_reference_id which should equal element_count. Any help would be great.
def url = new URL('https://api.nasa.gov/neo/rest/v1/feed?start_date=2019-05-10&end_date=2019-05-16&api_key=***')
def response = new groovy.json.JsonSlurper().parse( url )
def neo_references = response.near_earth_objects.collectMany{date,objects-> objects.collect{it.neo_reference_id} }
println neo_references
println neo_references.size()
assert response.element_count == neo_references.size()

How to parse a URL to fetch it's parameters in groovy?

I am new to groovy scripting and looking on to parse the URL and print it's parameter.
This url is : https://www.google.com/?aaa=111&bbb=222&ccc=33&dd=1484088989_b23f248ac6e5d9a9b47475526bb92ee1
How can i fetch dd parameter from the URL?
I appreciate your help!
You need to add a groovy script.
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
def testCase = context.testCase;
def testStep = testCase.getTestStepByName("NAME_TESTStepRequest");
def endpoint =testStep.getPropertyValue('Endpoint');
log.info endpoint;
def url = new URL(endpoint)
//def url = new URL("https://www.google.com/?aaa=111&bbb=222&ccc=33&dd=1484088989_b23f248ac6e5d9a9b47475526bb92ee1")
// get all query params as list
def queryParams = url.query?.split('&') // safe operator for urls without query params
// transform the params list to a Map spliting
// each query param
def mapParams = queryParams.collectEntries { param -> param.split('=').collect { URLDecoder.decode(it) }}
// assert the expected values
log.info mapParams['aaa']
//assert mapParams['aaa'] == '111'
log.info mapParams['bbb']
//assert mapParams['bbb']== 'abc'
log.info mapParams['dd']
//assert mapParams['dd']=='023423'
Please you check this post.Get query params from request url soapui using groovy

Soap UI: Groovy Script to call an API if the response is true

I am very new to use SoapUI. Writing test cases for my project APIs.
My requirement is to run a groovy script after an API call and if the response text of this API is "true", another API should call.
I found myself stuck to do this. Can anyone guide me to do this.
Thanks in advance!!!
I found answer but forgot to inform over here. I did asserted an script like this in TestStep:
def slurper = new groovy.json.JsonSlurper()
def responseJson = slurper.parseText(messageExchange.getResponseContent())
assert responseJson instanceof Map
assert responseJson.containsKey('authToken')
def id = "Bearer "+responseJson['authToken']
log.info(id.toString())
testRunner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(context.testCase.testSuite.project.getTestSuiteByName("TestSuite").getTestCaseByName("TestCas"), null)
def tcase = testRunner.testCase
def tstep = tcase.getTestStepByName("TestStep")
testContext = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext(tstep)
runner = tstep.run(testRunner, testContext)
Little idea for this :
def response = context.expand( '${TestRequest1#Response}' )
if ( response == 'true' )
{
testRunner.runTestStepByName( "TestRequest2")
}
Disable your first test Step(TestRequest1).

How to use setNodeValue in SOAPUI to update XML request

I'm new to SOAPUI and have several simple XML requests chained together. I want to use Groovy script to update an existing node on the Request side.
For example, I have GetRefData that starts:
<soapenv:Envelope xmlns:soapenv="aaa" xmlns:abc="bbb">
<soapenv:Header>
<abc:RequestHeader>
<CountryCode>US</CountryCode>
<MsgType>GetRefRq</MsgType>
</abc:RequestHeader>
</soapenv:Header>
etc...
I read the responses with no issues:
def GetRequestID = context.expand( '${GetRefData#Response#declare namespace abc=\'bbb\'; //abc:GetRefRq/MsgRqHeader/RequestId[1]}' )
How do I update the RequestId on the initial Request from 12345 to 53421? I've tried:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);
def request = context.expand('GetRefData#Request');
def requestHolder = groovyUtils.getXmlHolder(request);
requestHolder.namespaces["abc"] = "bbb";
def mypath = "//abc:GetRefRq/MsgRqHeader/RequestId[1]"
requestHolder.setNodeValue( mypath, "54321" )
But when I run it, although I get no errors and no updates.
Can someone please point this noob in the correct direction?
Try this :)
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context);
def request = context.expand('GetRefData#Request');
def requestHolder = groovyUtils.getXmlHolder(request);
//namespace declaration
// assuming your node is <bbb:RequestId>12345</bbb:RequestId>
def ns = "bbb"
requestHolder.setNodeValue("//"+ns+":RequestId", "54321" )
//to verify
log.info requestHolder.getNodeValue("//ns:RequestId" )

soapui shared datasource in groovy script

I have prepared a test case in SoapUI Open Source which loops over values in csv file and sends request for each set of values (taken care of by groovy script). I want to modify it so each thread for each new iteration uses value from next row of csv file.
import com.eviware.soapui.impl.wsdl.teststeps.*
def testDataSet = []
def fileName = "C:\\sSHhrTqA5OH55qy.csv"
new File(fileName).eachLine { line -> testDataSet.add( line.split(",") ) }
def myProps = new java.util.Properties();
myProps = testRunner.testCase.getTestStepByName("Properties");
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context );
def testCase = testRunner.testCase;
def testStep = testCase.getTestStepByName("TestRequest");
testRunner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(testCase, null);
testStepContext = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext(testStep);
while (true) {
for ( i in testDataSet ) {
myProps.setPropertyValue("parameter0",i[0]);
myProps.setPropertyValue("username",i[1]);
myProps.setPropertyValue("parameter1",i[2]);
myProps.setPropertyValue("password",i[3]);
testStep.getTestRequest().setUsername(myProps.getPropertyValue("username"))
testStep.getTestRequest().setPassword(myProps.getPropertyValue("password"))
testStep.run(testRunner, testStepContext);
}
}
I want to modify this script so each thread from the pool gets unique (next) unused value from data source
I tried to use newFixedThreadPool from java.util.concurrent as suggested here (Concurrency with Groovy), however I can't get it to work - either requests are duplicated or SoapUI crashes (I am new to concurrency).
Can you please help me to get it right?
I think this would work for you:
while (true) {
for ( i in testDataSet ) {
def th = Thread.start(){
myProps.setPropertyValue("parameter0",i[0]);
myProps.setPropertyValue("username",i[1]);
myProps.setPropertyValue("parameter1",i[2]);
myProps.setPropertyValue("password",i[3]);
testStep.getTestRequest().setUsername(myProps.getPropertyValue("username"))
testStep.getTestRequest().setPassword(myProps.getPropertyValue("password"))
testStep.run(testRunner, testStepContext);
}
th.join()
}
So, new threads would be created on each loop.
If you wanted to test out if its working you could place loginfo(s) in the code...
log.info("Thread Id: " + Thread.currentThread().getId() as String)
I don't see your point. SoapUi already gives you a datasource test step that accepts a csv file as input.
So once you have all these values you can transfer the properties and run the test.

Resources