DataGen in soapui or soapui pro? - rest

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" )
}

Related

how to use a pytest function to test different site using a different set of test data for each site such as staging/production

I have a set of pytest functions to test APIs, and test data is in a json file loaded by the pytest.mark.parametrize. Because the staging, production, and pre_production have different data but are similar, I want to save the test data in a different folder and use the same file name, in order to keep the python function clean. Site information is a new option from the command line of pytest. It doesn't work, pytest.mark.parametrize can't get the right folder to collect the test data.
This is in the conftest.py
#pytest.fixture(autouse=True)
def setup(request, site):
request.cls.site = site
yield
def pytest_addoption(parser):
parser.addoption("--site", action="store", default="staging")
#pytest.fixture(scope="session", autouse=True)
def site(request):
return request.config.getoption("--site")
This is in the test cases file:
#pytest.mark.usefixtures("setup")
class TestAAA:
#pytest.fixture(autouse=True)
def class_setup(self):
self.endpoint = read_data_from_file("endpoint.json")["AAA"][self.site]
if self.site == "production":
self.test_data_folder = "SourcesV2/production/"
else: // staging
self.test_data_folder = "SourcesV2/"
testdata.set_data_folder(self.test_data_folder)
#pytest.mark.parametrize("test_data", testdata.read_data_from_json_file(r"get_source_information.json"))
def test_get_source_information(self, test_data):
request_url = self.endpoint + f"/AAA/sources/{test_data['sourceID']}"
response = requests.get(request_url)
print(response)
I can use pytest.skip to skip the test data which is not for the current site.
if test_data["site"] != self.site:
pytest.skip("this test case is for " + test_data["site"] + ", skiping...")
But it will need to put all the test data in one file for staging/production/pre-production, and there will be a lot of skipped tests in the report, which is not my favorite.
Do you have any idea to solve this? How to pass a different file name to the parametrize according to the site?
Or, at least, how to let the skipped test not write logs in the report?
Thanks
The parametrize decorator is evaluated at load time, not at run time, so you will not be able to use it directly for this. You need to do the parametrization at runtime instead. This can be done using the pytest_generate_tests hook:
def pytest_generate_tests(metafunc):
if "test_data" in metafunc.fixturenames:
site = metafunc.config.getoption("--site")
if site == "production":
test_data_folder = "SourcesV2/production"
else:
test_data_folder = "SourcesV2"
# this is just for illustration, your test data may be loaded differently
with open(os.path.join(test_data_folder, "test_data.json")) as f:
test_data = json.load(f)
metafunc.parametrize("test_data", test_data)
class TestAAA:
def test_get_source_information(self, test_data):
...
If loading the test data is expansive, you could also cache it to avoid reading it for each test.

Downloading csv file using Play Framework?

I want to add to my app a simple button that on click will call an Action that will create a csv file from two lists I have and download it to the user computer.
This is my Action:
def createAndDownloadFile = Action {
val file = new File("newFile.csv")
val writer = CSVWriter.open(file)
writer.writeAll(List(listOfHeaders, listOfValues))
writer.close()
Ok.sendFile(file, inline = false, _ => file.getName)
}
but this is now working for me, the file is not getting downloaded from the browser...
im expecting to see the file get downloaded by the browser, i thought Ok.sendFile should do the trick..
thanks!
You can use Enumerators and streams for that. It should work like this:
val enum = Enumerator.fromFile(...)
val source = akka.stream.scaladsl.Source.fromPublisher(play.api.libs.streams.Streams.enumeratorToPublisher(enum))
Result(
header = ResponseHeader(OK, Map(CONTENT_DISPOSITION → "attachment; filename=whatever.csv.gz")),
body = HttpEntity.Streamed(source.via(Compression.gzip), None, None)
)
This will actually pipe the download through gzip. Just remove the .via(Compression.gzip) part if that is not needed.

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,

Jsoup post, selecting different options

http://www.myprotein.com/sports-nutrition/impact-whey-protein/10530943.html
I would like retrieve the prices for the different amounts, i.e. 1kg and 2.5kg
The first option is quite straightforward.
val page = Jsoup.connect("http://www.myprotein.com/sports-nutrition/impact-whey-protein/10530943.html").get()
println(page.select("div.media").select("h2.price").text.replaceAll("[a-zA-z\\s]", ""))
Getting the different options:
for (value <- page.getElementById("opts-7").getElementsByAttribute("value").asScala ) {
println(value.attr("value"))
}
However I have no idea about how to go on with the post, setting the cookies, headers etc. I prefer the speed and parsing abilities from Jsoup, however I am also considering taking the easy way out and using selenium to select the other options and parsing the source with jsoup.
So I decided to change to Selenium. It's selecting the right option with an emulated click however the price isn't updating. If I avoid closing the WebDriver and select the 2.5 kg manually it updates price accordingly
var driver: WebDriver = null
def main(args: Array[String]) {
setupWebDriver()
driver.navigate().to("http://www.myprotein.com/sports-nutrition/impact-whey-protein/10530943.html")
driver.findElement(By.xpath("//*[#id=\"opts-7\"]/option[2]")).click()
val temp = Jsoup.parse(driver.getPageSource)
println(temp.select("div.product-price").text())}
There's the main method and the WebDriver setup
def setupWebDriver() {
val binaryExe = "\\phantomjs.exe"
val BinaryChrome = "\\chromedriver.exe"
val caps: DesiredCapabilities = new DesiredCapabilities()
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, System.getProperty("user.dir") + binaryExe)
System.setProperty("phantomjs.binary.path", System.getProperty("user.dir") + binaryExe)
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + BinaryChrome)
caps.setJavascriptEnabled(true)
caps.setBrowserName(BrowserType.GOOGLECHROME)
driver = new ChromeDriver(caps)
driver.manage.timeouts.implicitlyWait(10, TimeUnit.SECONDS)}
Can anyone enlighten me on how I would get the price to update this way?

How to store and compare annotation (with Gold Standard) in GATE

I am very comfortable with UIMA, but my new work require me to use GATE
So, I started learning GATE. My question is regarding how to calculate performance of my tagging engines (java based).
With UIMA, I generally dump all my system annotation into a xmi file and, then using a Java code compare that with a human annotated (gold standard) annotations to calculate Precision/Recall and F-score.
But, I am still struggling to find something similar with GATE.
After going through Gate Annotation-Diff and other info on that page, I can feel there has to be an easy way to do it in JAVA. But, I am not able to figure out how to do it using JAVA. Thought to put this question here, someone might have already figured this out.
How to store system annotation into a xmi or any format file programmatically.
How to create one time gold standard data (i.e. human annotated data) for performance calculation.
Let me know if you need more specific or details.
This code seems helpful in writing the annotations to a xml file.
http://gate.ac.uk/wiki/code-repository/src/sheffield/examples/BatchProcessApp.java
String docXMLString = null;
// if we want to just write out specific annotation types, we must
// extract the annotations into a Set
if(annotTypesToWrite != null) {
// Create a temporary Set to hold the annotations we wish to write out
Set annotationsToWrite = new HashSet();
// we only extract annotations from the default (unnamed) AnnotationSet
// in this example
AnnotationSet defaultAnnots = doc.getAnnotations();
Iterator annotTypesIt = annotTypesToWrite.iterator();
while(annotTypesIt.hasNext()) {
// extract all the annotations of each requested type and add them to
// the temporary set
AnnotationSet annotsOfThisType =
defaultAnnots.get((String)annotTypesIt.next());
if(annotsOfThisType != null) {
annotationsToWrite.addAll(annotsOfThisType);
}
}
// create the XML string using these annotations
docXMLString = doc.toXml(annotationsToWrite);
}
// otherwise, just write out the whole document as GateXML
else {
docXMLString = doc.toXml();
}
// Release the document, as it is no longer needed
Factory.deleteResource(doc);
// output the XML to <inputFile>.out.xml
String outputFileName = docFile.getName() + ".out.xml";
File outputFile = new File(docFile.getParentFile(), outputFileName);
// Write output files using the same encoding as the original
FileOutputStream fos = new FileOutputStream(outputFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
OutputStreamWriter out;
if(encoding == null) {
out = new OutputStreamWriter(bos);
}
else {
out = new OutputStreamWriter(bos, encoding);
}
out.write(docXMLString);
out.close();
System.out.println("done");