How to use Groovy script in soapUi to loop multiple time - groovy

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

Related

ODI 12c Groovy - Automatically generate scenarios of a mapping with two physical layers

I want to create a groovy script that will generate two scenarios of a mapping that have two physical layers.
I have the code below, but it seems that it's not correct. I try to pass as value for "generateSecnario" method, the physical layer. Don't know if it's ok.
import oracle.odi.domain.project.finder.IOdiProjectFinder;
import oracle.odi.domain.model.finder.IOdiDataStoreFinder;
import oracle.odi.domain.project.finder.IOdiFolderFinder;
import oracle.odi.domain.mapping.finder.IMappingFinder;
import oracle.odi.domain.model.OdiDataStore;
import oracle.odi.domain.model.OdiModel;
import oracle.odi.domain.model.finder.IOdiModelFinder;
import oracle.odi.core.persistence.transaction.support.DefaultTransactionDefinition;
import oracle.odi.generation.support.OdiScenarioGeneratorImpl;
import oracle.odi.generation.IOdiScenarioGenerator;
import oracle.odi.domain.runtime.scenario.OdiScenario;
import oracle.odi.domain.mapping.Mapping;
import oracle.odi.domain.mapping.finder.IMappingFinder;
import oracle.odi.domain.runtime.scenario.finder.IOdiScenarioFinder;
import oracle.odi.domain.project.OdiProject;
txnDef = new DefaultTransactionDefinition()
tm = odiInstance.getTransactionManager()
tme = odiInstance.getTransactionalEntityManager()
txnStatus = tm.getTransaction(txnDef)
def fm = ((IMappingFinder) tme.getFinder(Mapping.class)) // shorcut to Find Mapping
def mappingList = fm.findAll().findAll {w-> w.getProject().getCode() == 'DL_GENERATE_MAPPINGS'
}
if (mappingList == null) {
println "Map is null"
}
ms = mappingList.iterator()
while (ms.hasNext()) {
ms_i = ms.next()
println ms_i.getName()
scenName = ms_i.getName();
stxnDef = new DefaultTransactionDefinition()
stm = odiInstance.getTransactionManager()
stme = odiInstance.getTransactionalEntityManager()
stxnStatus = stm.getTransaction(stxnDef)
OdiScenario sc = ((IOdiScenarioFinder) stme.getFinder(OdiScenario.class)).findLatestByName(scenName)
if (sc != null) {
println "Scenario already exist"
println sc
}
println("test");
odiInstance.getTransactionalEntityManager().persist(ms_i);
PhysicalDesignList = ms_i.getExistingPhysicalDesigns();
println("ceva" + PhysicalDesignList);
for (pd in PhysicalDesignList) {
if (pd.getName() == "DailyLayer") {
println("test1");
IOdiScenarioGenerator gene = new OdiScenarioGeneratorImpl(odiInstance);
OdiScenario newScen = gene.generateScenario(ms_i, scenName, "100");
} else if (pd.getName() == "CorrectionLayer") {
println("test2");
IOdiScenarioGenerator gene = new OdiScenarioGeneratorImpl(odiInstance);
OdiScenario newScen = gene.generateScenario(ms_i, scenName, "200");
}
}
println newScen
//tme.persist(newScen)
stm.commit(stxnStatus)
println "Created"
//odiInstance.close()
}
tm.commit(txnStatus)
Do you know how to do this ?
Thank you,
UPDATE 1
If I change "ms_i" in generateScenario method with "pd" (generating scenario for each physical layer instead of each mapping), I god this error:
Hi, I forgot to mention that I already replaced with pd and tried. When I run this first, I got this error:
No such property: newScen for class: Generate_scenarios_v1 (Subtract
18 from the error line number to account for the standard imports)
groovy.lang.MissingPropertyException: No such property: newScen for
class: Generate_scenarios_v1 at
org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at
org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
at
org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)
at Generate_scenarios_v1.run(Generate_scenarios_v1.groovy:80) at
groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:263)
at groovy.lang.GroovyShell.run(GroovyShell.java:518) at
groovy.lang.GroovyShell.run(GroovyShell.java:497) at
groovy.lang.GroovyShell.run(GroovyShell.java:170) at
oracle.di.studio.groovy.GroovyScriptRunInstance.run(GroovyScriptRunInstance.java:222)
After this, I i'll try to run it again, it goes into loop or something like that .. it doesn't do anything, like it's blocked by something. Maybe I need to close some connection and I don't do it ...
The first parameter of the generateScenario method you are invoking is of type IOdiScenarioSource. One of the implementation of this interface is MapPhysicalDesign, so you could pass that instead of your mapping.
OdiScenario newScen = gene.generateScenario(pd, scenName, "100");
I see you are using the same name for the two scenarii with a different version number. This might lead to some confusion in the long run, especially because executing version -1 of a scenario will take the latest version (so the correction in your case). I would recommend to use 2 different names (e.g. scenName+'_DAILY' and scenName+'_CORR')

How to evaluate a String which one like a classname.methodname in SoapUI with Groovy?

I have groovy code as below:
def randomInt = RandomUtil.getRandomInt(1,200);
log.info randomInt
def chars = (("1".."9") + ("A".."Z") + ("a".."z")).join()
def randomString = RandomUtil.getRandomString(chars, randomInt) //works well with this code
log.info randomString
evaluate("log.info new Date()")
evaluate('RandomUtil.getRandomString(chars, randomInt)') //got error with this code
I want to evaluate a String which one like a {classname}.{methodname} in SoapUI with Groovy, just like above, but got error here, how to handle this and make it works well as I expect?
I have tried as blew:
evaluate('RandomUtil.getRandomString(chars, randomInt)') //got error with this code
Error As below:
Thu May 23 22:26:30 CST 2019:ERROR:An error occurred [No such property: getRandomString(chars, randomInt) for class: com.hypers.test.apitest.util.RandomUtil], see error log for details
The following code:
log = [info: { println(it) }]
class RandomUtil {
static def random = new Random()
static int getRandomInt(int from, int to) {
from + random.nextInt(to - from)
}
static String getRandomString(alphabet, len) {
def s = alphabet.size()
(1..len).collect { alphabet[random.nextInt(s)] }.join()
}
}
randomInt = RandomUtil.getRandomInt(1, 200)
log.info randomInt
chars = ('a'..'z') + ('A'..'Z') + ('0'..'9')
def randomString = RandomUtil.getRandomString(chars, 10) //works well with this code
log.info randomString
evaluate("log.info new Date()")
evaluate('RandomUtil.getRandomString(chars, randomInt)') //got error with this code
emulates your code, works, and produces the following output when run:
~> groovy solution.groovy
70
DDSQi27PYG
Thu May 23 20:51:58 CEST 2019
~>
I made up the RandomUtil class as you did not include the code for it.
I think the reason you are seeing the error you are seeing is that you define your variables char and randomInt using:
def chars = ...
and
def randomInt = ...
this puts the variables in local script scope. Please see this stackoverflow answer for an explanation with links to documentation of different ways of putting things in the script global scope and an explanation of how this works.
Essentially your groovy script code is implicitly an instance of the groovy Script class which in turn has an implicit Binding instance associated with it. When you write def x = ..., your variable is locally scoped, when you write x = ... or binding.x = ... the variable is defined in the script binding.
The evaluate method uses the same binding as the implicit script object. So the reason my example above works is that I omitted the def and just typed chars = and randomInt = which puts the variables in the script binding thus making them available for the code in the evaluate expression.
Though I have to say that even with all that, the phrasing No such property: getRandomString(chars, randomInt) seems really strange to me...I would have expected No such method or No such property: chars etc.
Sharing the code for for RandomUtil might help here.

Using Groovy Script, How to access the dynamic soap request which is stored in MessageExchange in a Data-Driven Approach?

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();
}

Using Groovy to Loop and Execute Test Steps

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.

Jenkins Build Test Case pass fail count using groovy script

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)

Resources