How to export pdf attachment from soap response using groovy? - groovy

Although soap (free version) has an option to export document generated in response. Is there any groovy function to extract application/pdf file and store in my local folder ?

The following script should be able to save the attachment to a file.
Add the below script as Script Assertion to the current request step. Find the appropriate comments inline.
Source for the script is taken from here
/**
* Below script assertion will check
* if the response is not null
* there is an attachment
* and saves file to the specified location, by default saves into system temp
* directory
**/
//change file name as needed
def fileName = System.getProperty('java.io.tmpdir')+'/test.pdf'
//Get the response and check if the response is not null
def response = messageExchange.response
assert null != response, "response is null"
//Create output stream
def outFile = new FileOutputStream(new File(fileName))
//Check if there is one attachment in the response
assert 1 == messageExchange.responseAttachments.length, "Response attachments count not matching"
def ins = messageExchange.responseAttachments[0]?.inputStream
if (ins) {
//Save to file
com.eviware.soapui.support.Tools.writeAll( outFile, ins )
}
ins.close()
outFile.close()

Related

java.lang.NullPointerException with a POST call in Karate

I have a feature file like below:
*Feature: Create Quote in D365
Background:
* def myFeature = call read('D365_Authentication.feature')
* header Authorization = 'Bearer ' + myFeature.BearerToken
* def random_string =
"""
function(s){
var text = "";
var pattern = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(var i=0; i<s; i++)
text += pattern.charAt(Math.floor(Math.random() * pattern.length()));
return text;
}
"""
* url '<somehost>'
Scenario: Create Opportunity
Given path '<path>'
And def requestPayload = read('CreateOpportunity.json')
And set requestPayload.name = 'Temp Opportunity From Karate ' + random_string(10)
And set requestPayload.hsl_closedate = '2022-03-23T00:00:00.000Z'
And header Content-Type = 'application/json'
And request requestPayload
When method POST
Then status 204*
When running this, getting NullPointerException. Can anybody help me identify why this exception is coming.
Firstly you need to download the jar file specific karate version from https://github.com/karatelabs/karate/releases.
Please unfold the Assets link.
You can run the feature file so:
java - jar jarfinename -m xxx.feature

Automatic Data Driven tests in SoapUI via Groovy Script

as discussed HERE in soapUI free version i'm trying to call this WS:
<soap:Body>
<RequestParameters>
<Parameter name="key" value="SomeorderId"/>
</RequestParameters>
</soap:Body>
and i want to take the values of "key" from a local data.txt file on my desktop. the content of this file:
9999999991
9999999992
9999999993
to do so, i've created a test suite with below three test steps:
1.first step: a groovy script:
def data = new File('C:/Users/Polarick/Desktop/data.txt')
data.eachLine { orderId ->
context.orderId = orderId
//Get the step2, index of the step is 1
def step = context.testCase.getTestStepAt(1)
//Run the step2
step.run(testRunner, context)
}
//all the orders got executed,jump to step2, index is 2
testRunner.gotoStep(2)
2.second step: modifying request:
<Parameter name="MSISDN" value="${orderId}"/>
and asserting this script to it:
//Check if there is response
assert context.request, "Request is empty or null"
//Save the contents to a file
def saveToFile(file, content) {
if (!file.parentFile.exists()) {
file.parentFile.mkdirs()
log.info "Directory did not exist, created"
}
file.write(content)
assert file.exists(), "${file.name} not created"
}
def response = context.expand( '${Step2#Response}' )
def f = new File("C:/Users/Polarick/Desktop/${context.orderId}_Response.xml")
f.write(response, "UTF-8")
saveToFile(f, context.response)
3.Third step: a groovy script:
log.info "Test completed."
It all works fine and calls the WS for all lines existing in data.txt file sequentially, but i'm expecting to find a response .xml file per execution, for example:
C:/Users/Polarick/Desktop/9999999991_Response.xml
C:/Users/Polarick/Desktop/9999999992_Response.xml
C:/Users/Polarick/Desktop/9999999993_Response.xml
but there is no response file generated,
can you help?

Decoding a base64 string from JSON content in SOAPUI using groovy

I get a json response from a REST api that looks like below
{
"parentnode1": {
"childnode1": "abc12345-123-1234-1234-64a0251575f9",
"childnode2": "VAL1",
"childnode3": "format/pdf",
"childnode4": "name.pdf",
"base64content": "JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwRU9G"},
"messages": "This is a message"
}
I want to decode the value of "base64content" and then convert that into a pdf file and save it to a local directory. Is this possible in SOAP UI and Groovy ?
I came up with this groovy script but have not tested it in SOAPUI (have never used it). Try this and let me know what happens:
def jsonSlurper = new JsonSlurper()
def object = jsonSlurper.parseText (json_response)
String content_decoded = object.base64content.decodeBase64()
def file = new java.io.File("output.pdf")
FileOutputStream fos = new java.io.FileOutputStream(file)
fos.write( content_decoded )
fos.flush()
fos.close()


how to write all Soap Request available in Project using Soap UI Groovy

I have a soap project with 4 Test Suite,each Test Suite has some Test Case and each Test case has some test steps[Soap Request,Groovy Script]
I am able to access all the properties using mentioned code below , HOWEVER,code is writing blank request/response file in local system **
def Project = testRunner.testCase.testSuite.project;
for(def i=0;i<Project.testSuiteCount;i++)
{
log.info Project.getTestSuiteAt(i).name
def Suite = Project.getTestSuiteAt(i)
for(def j=0;j<Suite.testCaseCount;j++)
{
log.info Suite.getTestCaseAt(j).name
def TCase = Suite.getTestCaseAt(j)
for(def k=0;k < TCase.testStepCount;k++)
{
def TStep= TCase.getTestStepAt(k)
def req = context.expand('${'+TStep.name+'#Request}')
new File("D:/Directory/"+Suite.name+"_"+TCase.name+"_"+TStep.name+"_"+k+".txt").write( req )
}
}
}
** plz help to solve this, **
Actually there are multiple approaches to achieve this.
Below is the one of the approach.
Here is Groovy Script which writes the requests and responses.
This script assumes that user has already run the test suites so that responses are available to be saved.
Create a new test suite -> test case -> add Groovy Script test step and copy the below script into it.
Groovy Script:
/**
* This groovy script saves the request and response
* And this script will be able to write the responses
* into files if and only if there is response available
**/
import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep
//Change direcoty path if required
def directoryToSave = 'D:/directory'
//Not required to change the script beyond this point
//date time is appended to the file name
def dt = new Date().format('yyyyMMdd_HHmmss')
//Closure to save the file
def saveToFile(file, content) {
if (!file.parentFile.exists()) {
file.parentFile.mkdirs()
log.info "Directory did not exist, created"
}
if (content) {
log.info "Writing the content into file :${file.name}"
file.write(content)
assert file.exists(), "${file.name} not created"
} else {
log.warn "the content is empty, not writing the content into file"
}
}
//Get the project object
def project = context.testCase.testSuite.project
//Loop thru the project and save the request and responses
project.testSuiteList.each { suite ->
suite.testCaseList.each { kase ->
kase.testStepList.each { step ->
if (step instanceof WsdlTestRequestStep) {
def reqFilePath = new File("${directoryToSave}/${suite.name}_${kase.name}_${step.name}_request${dt}.xml")
def resFilePath = new File("${directoryToSave}/${suite.name}_${kase.name}_${step.name}_response${dt}.xml")
saveToFile(reqFilePath, step.testRequest.requestContent)
saveToFile(resFilePath, step.testRequest.responseContent)
saveToFile(step)
} else {
log.info "Ignoring as the step type is not Soap request"
}
}
}
}

groovy.lang.MissingPropertyException: No such property: file for class: Script7 error at line 5

I am writing groovy script to save raw soap request & response and i get this error:
groovy.lang.MissingPropertyException: No such property: file for class: Script7 error at line 5
Here is the Script:
def myOutFile = context.expand( '${#TestSuite#fileName}' )+"_PostPaid-Success_Payment_BillInqReq.xml"
def response = context.expand( '${BillInq#Request}' )
def f = new File(myOutFile)
f.write(response, "UTF-8")
file.write(context.rawRequest,'utf-8')
Please follow the steps below:
Go to Test Suite PostPaid
Add a custom property say DATA_STORE_PATH and its value to a directory name where you like to save the requests and responses
Go to test case PostPaid_Success_Payment
Disable the Step 2 & Step 3 i.e., SaveInquiryReq and SaveInquiryResponse steps. or you may remove altoger as well if no other work is done apart from save the request & response respectively.
Click on step1 BillInq, click on assertions, Choose Script Assertion, see here for more details how to add script assertion
Have below script and click ok
Now you run the step1, you should be able to see the request and responses saved in the above mentioned directory
/**
* This script logs both request and response
*/
assert context.response, "Response is empty or null"
assert context.request, "Request is empty or null"
//Save the contents to a file
def saveToFile(file, content) {
if (!file.parentFile.exists()) {
file.parentFile.mkdirs()
log.info "Directory did not exist, created"
}
file.write(content)
assert file.exists(), "${file.name} not created"
}
def dirToStore = context.expand('${#TestSuite#DATA_STORE_PATH}')
def currentStepName = context.currentStep.name
def requestFileName = "${dirToStore}/${currentStepName}_request.xml"
def responseFileName = "${dirToStore}/${currentStepName}_response.xml"
//Save request & response to directory
saveToFile(new File(requestFileName), context.rawRequest)
saveToFile(new File(responseFileName), context.response)

Resources