Use excel file variables in SOAP request in SoapUI - soap

I've faced with a problem. I'm new in SoapUI.
I must read excel file and then put some variables in the soap request. This is what I've done:
I've add a groovy script to get the excel file data:
import jxl.*
Workbook workbook = Workbook.getWorkbook(new File("C:\\PATH\\TestData.xls"))
Sheet sheet1 = workbook.getSheet("Sheet1")
def rows = sheet1.getRows()
def cols = sheet1.getColumns()
log.info "Row Count =" + rows
log.info "Column Count =" + cols
def array = []
for(i=1;i<rows;i++) {
for(j=0;j<cols;j++) {
Cell cell = sheet1.getCell(j,i)
def variable = cell.getContents()
log.info cell.getContents()
array << variable
}
}
return array
array returns: 10 and 20.
And this is a soap request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
<soapenv:Header/>
<soapenv:Body>
<tem:Add>
<tem:intA>10</tem:intA>
<tem:intB>10</tem:intB>
</tem:Add>
</soapenv:Body>
</soapenv:Envelope>
Can I somehow call a groovy script and put variables in
<tem:intA>10</tem:intA>
<tem:intB>20</tem:intB>
Instead of 10 and 20, I should call a groovy script method and put data, which I've taken from excel file.

Since your use-case is trivial: just two variables to be substituted, you can just use two properties.
Change the return array in your script to something like:
testCase.setPropertyValue("intA", array[0].toString())
testCase.setPropertyValue("intB", array[1].toString())
And then your request to:
<tem:intA>${#TestCase#intA}</tem:intA>
<tem:intB>${#TestCase#intB}</tem:intB>

Related

Convert XML like String to PySpark Dataframe

I'm using azure.storage.queue's receive_messages() function in databricks to pull messages from a azure queue. The response looks like xml but it is really just a string:
<?xml version="1.0" encoding="utf-16"?>
<root>
<col1>123</col1>
<col2>1</col2>
<col3>Unknown</col3>
<col4>Dog</col4>
<col5>Owner</col5>
<col6>-1</col6>
<col7>Owner</col7>
<col8></col8>
</root>
When I write the response to a list, it looks like:
'<root>\r\n <col1>123</col1>\r\n <col2>1</col2>\r\n <col3>Unknown</col3>\r\n <col4>Dog</col4>\r\n <col5>Owner</col5>\r\n <col6>-1</col6>\r\n <col7>Owner</col7>\r\n <col8></col8>\r\n</root>'
I know that I can split on \r\n with something like:
l = [x.strip().split(' ') for x in a[0].split('\r\n')]
l
This gives:
['root'],
['<col1>123</col1>'],
['<col2>1</col2>'],
['<col3>Unknown</col3>'],
['<col4>Dog</col4>'],
['<col5>Owner</col5>'],
['<col6>-1</col6>'],
['<col7>Owner</col7>'],
['<col8></col8'],
['</root>']]
I'm not sure if this is the best route and I don't want to hard code each value into the spark dataframe, because I need to iterate through all messages in the queue. Looking for a solution that converts each 'col' into a header and then grabs the value between 'tags'.
Here is an answer:
data=[]
for message in response:
#print(message.content)
soup = BeautifulSoup(message.content, "xml")
c=soup.find_all('col1')
c1=soup.find_all('col2')
c2=soup.find_all('col3')
c3=soup.find_all('col4')
c4=soup.find_all('col5')
c5=soup.find_all('col6')
c6=soup.find_all('col7')
c7=soup.find_all('col8')
for i in range(0,len(c)):
rows=[c[i].get_text(),
c1[i].get_text(),
c2[i].get_text(),
c3[i].get_text(),
c4[i].get_text(),
c5[i].get_text(),
c6[i].get_text(),
c7[i].get_text()]
data.append(rows)
#print(data)
out_df = spark.createDataFrame(data,schema = ['c','c1','c2','c3','c4',
'c5','c6','c7'])
This was faster, but requires the response to always be in the same order, which mine is.
data=[]
for message in response:
#print(message.content)
root=etree.fromstring(message.content.encode('utf-16'))
arr=[]
for child in root:
r=child.text
arr.append(r)
data.append(arr)
out_df = spark.createDataFrame(data,schema = ['c','c1','c2','c3','c4',
'c5','c6','c7'])
display(out_df)

How to compare responses of two methods in SoapUI

I am executing a SOPA method on two environments(Dev and UAT) in SopaUI free version and want to compare the responses to check data mismatch, please suggest any solution for the same.
Response Format-
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetAccountsResponse xmlns="http://services.multichoice.co.za/SelfCare">
<GetAccountsResult xmlns:a="http://datacontracts.multichoice.co.za/SelfCare" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Account>
<a:afterDue121To150>0</a:afterDue121To150>
<a:afterDue151To180>0</a:afterDue151To180>
<a:afterDue180UpField>0</a:afterDue180UpField>
<a:afterDue1To30Field>0</a:afterDue1To30Field>
<a:afterDue31To60Field>0</a:afterDue31To60Field>
<a:afterDue61To90Field>0</a:afterDue61To90Field>
<a:afterDue91To120Field>0</a:afterDue91To120Field>
<a:currency>NGN</a:currency>
<a:currentAmount>0</a:currentAmount>
<a:defaultCurrencytotalBalance>0</a:defaultCurrencytotalBalance>
<a:defaultCuurencyCode>NGN</a:defaultCuurencyCode>
<a:invoicePeriod>1</a:invoicePeriod>
<a:isPrimary>true</a:isPrimary>
<a:lastInvoiceAmount>0</a:lastInvoiceAmount>
<a:lastInvoiceDate>2017-02-19T15:52:54</a:lastInvoiceDate>
<a:methodOfPayment>Cash</a:methodOfPayment>
<a:number>3112</a:number>
<a:paymentDueDate>2016-11-10T00:00:00</a:paymentDueDate>
<a:segmentation>Customer Segment N</a:segmentation>
<a:status>Suspended</a:status>
<a:totalBalance>0</a:totalBalance>
<a:type>Ges</a:type>
</a:Account>
</GetAccountsResult>
</GetAccountsResponse>
</s:Body>
</s:Envelope>
//Step 1: Set DEV environment in your soap request using ReqProps = testRunner.testCase.getTestStepByName("stepname as in soapui suite"
ReqProps.setPropertyValue("Endpoint","https://dev:endpoint")
//Step 2: Run the DEV step and save response in some variable testRunner.runTestStepByName("stepname as in soapui suite")
DEvResponse = ReqProps.getPropertyValue("Response")
// Step 3: Repeat Same step for UAT environment and take response in variable UATResponse
// Step 4: Compare 2 responses using `DetailedDiff diffInRes = new DetailedDiff(new Diff(DEVRes, UATRes))
List differencesArray = diffInRes.getAllDifferences()`
// Step 5 . Take array size to verify if XMLs match. If XMLs does not match you can print differences and get all mismatches from array "differencesArray"

How do i pass ## separated values in Scala?

Consider the following scenario:
["123##456","789##101112","131415##161718","192021##222324"]
first-id: 123, second-id: 456...
I get the above as two different sets of ids in the JSON payload of my response.
Saving the values via
.check(jsonPath("$.data[*].Id").findAll.saveAs("Id"))
works perfectly fine for me.
But now I need to pass the above-mentioned ids in the next request of post method, which comes as
["123##456","789##101112","131415##161718","192021##222324"]
So how to achieve that? If you could explain with an example please?
You could use split, something like:
var data = Array("123##456","789##101112","131415##161718","192021##222324");
for(i <- 0 until data.length){
var ids = data(i).split("##");
println("first id is: " + ids(0));
println("second id is: " + ids(1));
}

Groovy script for count value matches with offset

<... count="6" offset="3,2,7,1,4,5"/>
from the above snippet, i want to verify number of offset values should get match with count value. Please help to get SOAPUI REST services groovy script for this one.
Thanks!
Your question it's not clear so supposing that you've something like:
<myTag count="6" offset="3,2,7,1,4,5"/>
You can use XmlSlurper in groovy script to validate your requirement as follows:
def xmlStr = '<myTag count="6" offset="3,2,7,1,4,5"/>'
def xml = new XmlSlurper().parseText(xmlStr)
// use # notation to acces attributes
def count = xml.#count
def offset = xml.#offset.toString().split(',')
// assert that count matches the length of the array
assert count == offset.length
Anyways consider to provide more details and what you tried as #Opal suggest in it's comment.
Hope it helps,

DataGen in soapui or soapui pro?

I want to test Restful web service in SoapUI. For that, I need to read values from Excel and pass that to request.
I searched in net, I found that it is possible through DataGen TestStep. I have SoapUI, but I couldn't find that option.
Can someone please tell if DataGen TestStep is available in SoapUI-4.5.1 or SoapUI Pro.
I am 99% sure that the data sources and such are only in SoapUI pro. You can accomplish the same thing in groovy scripts, though, but you would probably be better off reading from a text file as opposed to a spreadsheet.
The step is available only in Soap UI Pro only(Ready API)
In free version that is Soap UI, you can use POI way of reading an excel file via groovy scripting and pass those values in your input request.
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.usermodel.DataFormatter;
def fs = new FileInputStream("F:\\Gaurav\\soapui\\readFile.xlsx")
def wb = new XSSFWorkbook(fs)
def ws = wb.getSheet("Sheet1")
def r = ws.getPhysicalNumberOfRows()
for(def i =0 ; i < r ; i++)
{
def row = ws.getRow(i);
def c=row.getPhysicalNumberOfCells()
for(def j=0; j <c ; j++)
{
def cell= row.getCell(j)
// to convert everything to a String format
DataFormatter formatter = new DataFormatter()
def cellValue=formatter.formatCellValue(cell)
log.info cellValue
}
}
// Above is the code to read from excel. Once you have read the values, you can // store the values in property
testRunner.testCase.setPropertyValue(tcprop,"cellValue")
then in your request you can expand it like below
${#TestCase#tcprop}
This way you can achieve the same DataGen thing in Soap UI free version 4.5
So, there is an option in SoapUI Setup Script that could be run in advance
You can convert your Excel to csv or text file and handle the date from there.
I've done some testing with REST services, used only reading from the text file feature.
the code like this:
//Load the text file
def inputFile = new File("C://Temp//whatever");
//Create an empty list...
def mega_List = [];
//...and then populate it with the contents
// of the text file.
addSomeThingToList = {mega_List.add(it)};
inputFile.eachLine(addSomeThingToList);
//...and assign its value to the Test Case Property
def tc = testRunner.testCase;
//Randomly pick an item from the list...
def index = context.expand( '${#TestCase#index}' ).toInteger()
if ( index < mega_List.size() ) {
def id = mega_List.get(index);
index++
tc.setPropertyValue("id", id);
tc.setPropertyValue("index", index.toString());
}
else {
tc.setPropertyValue("index", "0");
tc.setPropertyValue("id", "0");
testrunner.cancel( "time to go home" )
}