I'm trying to do dynamic testing where I query the database, use Groovy to loop through and gather the data I need, and execute the validation web service with the results from the database call.
Here is my code:
response = context.expand('${JDBC Get User Task#ResponseAsXml}')
String userTaskId
int r = 1
def root = new XmlSlurper().parseText(response)
tc = testRunner.testCase
ts = tc.testSteps["Get usertask by id"]
root.ResultSet.Row.each{ row ->
log.info "Data for row: " + r.toString()
userTaskId = row["USER_TASKS.USER_TASK_ID"]
tc.setPropertyValue("result", userTaskId)
ts.run(testRunner, context)
r++
}
The problem I'm having is that if 3 results are returned, the only one that gets executed is the 3rd time into the validation web service.
Related
I am using a Groovy script to fetch data from excel data source for SOAP UI request message. Script works till 100 rows beyond that it hang and goes to unresponsive in soap ui.
This groovy script works in SOAP UI for 50 records in excel but I need to use excel which has 22k rows.
This is the complete hierarchy of the groovy script:-
https://www.belatrixsf.com/blog/trick-for-soapui-free-in-eight-steps/
// IMPORT THE LIBRARIES WE NEED
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*
// DECLARE THE VARIABLES
def myTestCase = context.testCase //myTestCase contains the test case
def counter,next,previous,size //Variables used to handle the loop and to move inside the file
Workbook workbook1 = Workbook.getWorkbook(new File("c:\\dataFile.xls")) //file containing the data
Sheet sheet1 = workbook1.getSheet(0) //save the first sheet in sheet1
size= sheet1.getRows().toInteger() //get the number of rows, each row is a data set
propTestStep = myTestCase.getTestStepByName("Property - Looper") // get the Property TestStep object
propTestStep.setPropertyValue("Total", size.toString())
counter = propTestStep.getPropertyValue("Count").toString() //counter variable contains iteration number
counter = counter.toInteger() //
next = (counter > size-2? 0: counter+1) //set the next value
// OBTAINING THE DATA YOU NEED
Cell u = sheet1.getCell(0,counter) // getCell(column,row) //obtains user
Cell p = sheet1.getCell(1,counter) // obtains password
workbook1.close() //close the file
////////////////////////////////////
usr = u.getContents()
pass = p.getContents()
propTestStep.setPropertyValue("user", usr) //the value is saved in the property
propTestStep.setPropertyValue("pass", pass) //the value is saved in the property
propTestStep.setPropertyValue("Count", next.toString()) //increase Count value
next++ //increase next value
propTestStep.setPropertyValue("Next", next.toString()) //set Next value on the properties step
//Decide if the test has to be run again or not
if (counter == size-1)
{
propTestStep.setPropertyValue("StopLoop", "T")
log.info "Setting the stoploop property now..."
}
else if (counter==0)
{
def runner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(testRunner.testCase, null)
propTestStep.setPropertyValue("StopLoop", "F")
}
else
{
propTestStep.setPropertyValue("StopLoop", "F")
}
Expected output groovy script should not hang while fetching 22k records from excel.
I am new to SoapUi. I am exploring on how multiple request in soapUi is done using groovy script.
below is the example that im trying to do, based on example that i found through "googling"
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.model.testsuite.*;
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner
import java.util.Random
import com.eviware.soapui.model.testsuite.TestRunner.Status
// Define your testCase pointer
//def testcase = testRunner.testCase.testSuite.project.testSuites["TestSuite - User Management REST API"].getTestCaseByName ("Authenticate User")
def counterUser = testRunner.testCase.testSuite.getPropertyValue( "counter" )
int value = counterUser.toInteger()
String tester = ""
30.times {
value = value + 1
tester = "tester " + value.toString()
testRunner.testCase.testSuite.setPropertyValue( "userName", tester )
testRunner.runTestStepByName("POST - createUser - Create a User")
}
testRunner.testCase.testSuite.setPropertyValue( "counter", value.toString() )
I want to create a 30 users which start from Tester1...tester2.....tester30.
Is it possible to do this way? I keep getting an error such as NullPointerException at this line
int value = counterUser.toInteger()
I got what you say.
That is because, initially there is no value for counter which results to null and you are applying toInteger() over it.
Just change:
From:
int value = counterUser.toInteger()
To:
int value = counterUser?.toInteger() ?: 0
I am trying a data driven approach in soap ui using groovy script and I wanted to export each of the dynamic request and response from MessageExchange to an Excel sheet. I am using the input data Excel file "dataFile.xls" for a simple "Login" operation. It consists of 2 fields Username and Password with 4 records. My script is doing a data driven approach and executing all the records from the excel file. But I wanted to export all the four dynamic request and response into an Excel file "Output.xls". My soap pack is having 2 groovy test request(one for data driver and the other for looping), one property test step to hold the input element properties and temporary variables, one soap test request "login". Below is the code snippet I am using in the "data driver" groovy test step.
// IMPORT THE LIBRARIES WE NEED
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*
import com.eviware.soapui.model.iface.MessageExchange
// DECLARE THE VARIABLES
def myTestCase = context.testCase //myTestCase contains the test case
log.info(myTestCase)
def counter,next,previous,size //Variables used to handle the loop and to move inside the file
Workbook workbook1 = Workbook.getWorkbook(new File("d:\\Groovy videos\\dataFile.xls")) //file containing the data
Sheet sheet1 = workbook1.getSheet(0) //save the first sheet in sheet1
size = sheet1.getRows().toInteger() //get the number of rows, each row is a data set
log.info(size)
propTestStep = myTestCase.getTestStepByName("Property - Looper") // get the Property TestStep object
log.info(propTestStep)
req = myTestCase.getTestStepByName("login").getProperty("Request").getValue()
//log.info(req)
propTestStep.setPropertyValue("Total", size.toString())
counter = propTestStep.getPropertyValue("Count").toString() //counter variable contains iteration number
counter = counter.toInteger() //
next = (counter > size-2? 0: counter+1) //set the next value
// OBTAINING THE DATA YOU NEED
Cell u = sheet1.getCell(0,counter) // getCell(column,row) //obtains user
Cell p = sheet1.getCell(1,counter) // obtains password
workbook1.close() //close the file
////////////////////////////////////
usr = u.getContents()
pass = p.getContents()
propTestStep.setPropertyValue("user", usr) //the value is saved in the property
propTestStep.setPropertyValue("pass", pass) //the value is saved in the property
propTestStep.setPropertyValue("Count", next.toString()) //increase Count value
next++ //increase next value
propTestStep.setPropertyValue("Next", next.toString()) //set Next value on the properties step
WritableWorkbook workbook2 = Workbook.createWorkbook(new File("d:\\output.xls"))
WritableSheet sheet2 = workbook2.createSheet("Request", 0)
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def temp=testRunner.testCase.testSteps["login"]
def testStepContext = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext(temp)
def reqq = testStepContext.getRequestContent()
log.info(reqq)
//def temp=testRunner.testCase.testSteps.testRequest.getRequestContent()
//holder = groovyUtils.getXmlHolder(messageExchange.requestContent)
log.info("request : "+temp)
Label label1 = new Label(0, 6, temp);
sheet2.addCell(label1);
workbook2.write()
workbook2.close()
//Decide if the test has to be run again or not
if (counter == size-1)
{
propTestStep.setPropertyValue("StopLoop", "T")
log.info "Setting the stoploop property now..."
}
else if (counter==0)
{
def runner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(testRunner.testCase, null)
propTestStep.setPropertyValue("StopLoop", "F")
}
else
{
propTestStep.setPropertyValue("StopLoop", "F")
}
I am getting the fault
"groovy.lang.MissingMethodException: No signature of method: com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext.getRequestContent() is applicable for argument types: () values: [] error at line: 50"
Could some one please help me in this.
The main objective is to get all the dynamic request and response from the MessageExchange and export all the data into the excel sheet.
Your program throws the exception there:
def testStepContext = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext(temp)
def reqq = testStepContext.getRequestContent()
log.info(reqq)
The exception is pretty clear MissingMethodException so the problem is that com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext doesn't have getRequestContent() method.
Anyway in your code you only use reqq on log.info(reqq)... then without analyzing the whole code the easy solution to solve the problem is simply remove this lines due they are useless.
You better make use of project level event "TestRunListener.afterStep" to accomplish your task.
In this event you'll have access to testRunner, context & testStepResult Objects. The following code snippet can help you.
For Soap Services:
if (context.getCurrentStep() instanceof WsdlTestRequestStep) {
WsdlTestStepResult soapResult= (WsdlTestStepResult) testStepResult;
log.info "Request: "+soapResult.getRequestContent();
log.info "Response: "+soapResult.getResponseContent();
}
For Rest Services:
if (context.getCurrentStep() instanceof RestTestRequestStep) {
RestRequestStepResult restResult= (RestRequestStepResult) testStepResult;
log.info "Request: "+restResult.getRequestContent();
log.info "Response: "+restResult.getResponseContent();
}
I am using free version of soapui. In my load test, I want to read request field value from a text file. The file looks like following
0401108937
0401109140
0401109505
0401110330
0401111204
0401111468
0401111589
0401111729
0401111768
In load test, for each request I want to read this file sequentially. I am using the code mentioned in Unique property per SoapUI request using groovy to read the file. How can I use the values from the file in a sequential manner?
I have following test setup script to read the file
def projectDir = context.expand('${projectDir}') + File.separator
def dataFile = "usernames.txt"
try
{
File file = new File(projectDir + dataFile)
context.data = file.readLines()
context.dataCount = context.data.size
log.info " data count" + context.dataCount
context.index = 0; //index to read data array in sequence
}
catch (Exception e)
{
testRunner.fail("Failed to load " + dataFile + " from project directory.")
return
}
In my test, I have following script as test step. I want to read the current index record from array and then increment the index value
def randUserAccount = context.data.get(context.index);
context.setProperty("randUserAccount", randUserAccount)
context.index = ((int)context.index) + 1;
But with this script, I always get 2nd record of the array. The index value is not incrementing.
You defined the variable context.index to 0 and just do +1
You maybe need a loop to read all values.
something like this :
for(int i=0; i <context.data.size; i++){
context.setProperty("randUserAccount", i);
//your code
}
You can add this setup script to the setup script section for load test and access the values in the groovy script test step using:
context.LoadTestContext.index =((int)context.LoadTestContext.index)+1
This might be a late reply but I was facing the same problem for my load testing for some time. Using index as global property solved the issue for me.
Index is set as -1 initially. The below code would increment the index by 1, set the incremented value as global property and then pick the context data for that index.
<confirmationNumber>${=com.eviware.soapui.SoapUI.globalProperties.setPropertyValue( "index", (com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "index" ).toLong()+1 ).toString()); return (context.data.get( (com.eviware.soapui.SoapUI.globalProperties.getPropertyValue( "index" )).toInteger())) }</confirmationNumber>
I want to fetch Total TestCase PASS and FAIL count for a build using groovy script. I am using Junit test results. I am using Multiconfiguration project , so is there any way to find this information on a per configuration basis?
If you use the plugin https://wiki.jenkins-ci.org/display/JENKINS/Groovy+Postbuild+Plugin, you can access the Jenkins TestResultAction directly from the build ie.
import hudson.model.*
def build = manager.build
int total = build.getTestResultAction().getTotalCount()
int failed = build.getTestResultAction().getFailCount()
int skipped = build.getTestResultAction().getSkipCount()
// can also be accessed like build.testResultAction.failCount
manager.listener.logger.println('Total: ' + total)
manager.listener.logger.println('Failed: ' + failed)
manager.listener.logger.println('Skipped: ' + skipped)
manager.listener.logger.println('Passed: ' + (total - failed - skipped))
API for additional TestResultAction methods/properties http://javadoc.jenkins-ci.org/hudson/tasks/test/AbstractTestResultAction.html
If you want to access a matrix build from another job, you can do something like:
def job = Jenkins.instance.getItemByFullName('MyJobName/MyAxisName=MyAxisValue');
def build = job.getLastBuild()
...
For Pipeline (Workflow) Job Type, the logic is slightly different from AlexS' answer that works for most other job types:
build.getActions(hudson.tasks.junit.TestResultAction).each {action ->
action.getTotalCount()
action.getFailCount()
action.getSkipCount()
}
(See http://hudson-ci.org/javadoc/hudson/tasks/junit/TestResultAction.html)
Pipeline jobs don't have a getTestResultAction() method.
I use this logic to disambiguate:
if (build.respondsTo('getTestResultAction')) {
//normal logic, see answer by AlexS
} else {
// pipeline logic above
}
I think you might be able to do it with something like this:
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
File fXmlFile = new File("junit-tests.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
println("Total : " + doc.getDocumentElement().getAttribute("tests"))
println("Failed : " +doc.getDocumentElement().getAttribute("failures"))
println("Errors : " +doc.getDocumentElement().getAttribute("errors"))
I also harvest junit xml test results and use Groovy post-build plugin https://wiki.jenkins-ci.org/display/JENKINS/Groovy+Postbuild+Plugin to check pass/fail/skip counts. Make sure the order of your post-build actions has harvest junit xml before the groovy post-build script.
This example script shows how to get test result, set build description with result counts and also version info from a VERSION.txt file AND how to change overall build result to UNSTABLE in case all tests were skipped.
def currentBuild = Thread.currentThread().executable
// must be run groovy post-build action AFTER harvest junit xml
testResult1 = currentBuild.testResultAction
currentBuild.setDescription(currentBuild.getDescription() + "\n pass:"+testResult1.result.passCount.toString()+", fail:"+testResult1.result.failCount.toString()+", skip:"+testResult1.result.skipCount.toString())
// if no pass, no fail all skip then set result to unstable
if (testResult1.result.passCount == 0 && testResult1.result.failCount == 0 && testResult1.result.skipCount > 0) {
currentBuild.result = hudson.model.Result.UNSTABLE
}
currentBuild.setDescription(currentBuild.getDescription() + "\n" + currentBuild.result.toString())
def ws = manager.build.workspace.getRemote()
myFile = new File(ws + "/VERSION.txt")
desc = myFile.readLines()
currentBuild.setDescription(currentBuild.getDescription() + "\n" + desc)