How Groovy can save console output to file? - groovy

i have a project in Soapui and a groovy code which run all tests of the project.
The result can be seen in the output console.
So what i want is to to save the content of the output ina file.
in Java we can do this:
//create a buffered reader that connects to the console, we use it so we can read lines
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//read a line from the console
String lineFromInput = in.readLine();
//create an print writer for writing to a file
PrintWriter out = new PrintWriter(new FileWriter("c:/temp7/output.txt"));
//output to the file a line
out.println(lineFromInput);
//close the file
out.close();
Is there an equivalent code in groovy ?
THank you

Of course you can read the console output.
But you ned to execute your tests from the GUI and not from command line with testrunner.
// Can be altered to 'soapUI log', 'http log', 'jetty log', 'error log' etc.
def logArea = com.eviware.soapui.SoapUI.logMonitor.getLogArea( "http log" );
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
if( logArea !=null )
{
def model = logArea.model
// only continue of logArea not empty
if( model.size > 0 )
for( c in 0..(model.size-1) )
// DO SOMETHING HERE... could write to file, could run assertions, etc.
writeToFile(model.getElementAt(c))
}

Related

How can I export a test report from SoapUI as Json?

I am running some API tests and I am using a groovy script to get out the test run report (SoapUI free version). My issue is that the reports comes in a .csv format, although I need it to be a .json format.
First the reports were generated as .csv, but now we must switch to json and I can`t figure out on what to change to the script to export as .json.
try {
// 1. Create a "SoapUIResults" folder in the project path
// Retrieve the project root folder
def projectPath = new com.eviware.soapui.support.GroovyUtils(context).projectPath
// Specify a folder inside project root to store the results
String folderPath = projectPath + "/SoapUIResults";
// Create a File object for the specified path
def resultFolder = new File(folderPath);
// Check for existence of folder and create a folder
if(!resultFolder.exists())
{
resultFolder.mkdirs();
}
/* ------------------------------------------------------------------------------- */
// 2. Create a subfolder (with timestamp) to store the request-response local copy
// Retrieve the latest execution date-time
Date d = new Date();
def executionDate = d.format("dd-MMM-yyyy HH_mm");
// Specify the subfolder path with name Request-Response_CurrentTimeStamp
String subfolderPath1 = folderPath+ "/Request-Response_"+executionDate;
// Create this sub-folder
new File(subfolderPath1).mkdirs();
/* ------------------------------------------------------------------------------- */
// 3. Create another subfolder "JSON Reports" to store the reports file
// Specify the subfolder path with name JSON Reports
String subfolderPath2 = folderPath+ "/JSON Reports";
// Create this sub-folder
new File(subfolderPath2).mkdirs();
/* ------------------------------------------------------------------------------- */
// 4. Create a Report.json file inside the JSON Reports folder
// Create a File object for Report json file (with timestamp)
def reportFile = new File(subfolderPath2, "Report_"+executionDate+".json");
// Check for existence of report file and create a file
if(!reportFile.exists())
{
reportFile.createNewFile();
// Create required column names in the report file
reportFile.write('"Test Suite","Test Case","Test Step","Step Type","Step Status",'
+'"Result message","Execution Date"');
}
/* ------------------------------------------------------------------------------- */
// 5. Inserting data in the file
// Iterate over all the test steps results
for(stepResult in testRunner.getResults())
{
// Retrieve Test Suite name
def testSuite = testRunner.testCase.testSuite.name;
// Retrieve Test Case name
def testCase = testRunner.testCase.name;
// Retrieve Test Step
def testStep = stepResult.getTestStep();
// Retrieve Test Step name
def testStepName = testStep.name
// Retrieve Test Step type
def type = testStep.config.type
// Retrieve Test Step status
def status = stepResult.getStatus()
// Creating new line in report file
reportFile.append('\n');
// Write all the necessary information in the file
reportFile.append('"' + testSuite + '",');
reportFile.append('"' + testCase + '",');
reportFile.append('"' + testStepName + '",');
reportFile.append('"' + type + '",');
reportFile.append('"' + status + '",');
// Retrieve the test result messages
reportFile.append('"');
for(resMessage in stepResult.getMessages())
{
// Write messages and separate multiple messages by new line
reportFile.append('Message:' + resMessage + '\n');
}
reportFile.append('",');
//Write executionDate in the file
reportFile.append('"' + executionDate + '",');
/* ------------------------------------------------------------------------------- */
// 6. Extract the request and response and save it to external file
// Verify if the test step type is request: SOAP project or restrequest: REST project
if((type=="request").or(type=="restrequest"))
{
// Extract the request from the test step
def extRequest = testStep.properties["Request"].value;
// Create a file in the reports folder and write the request
// Naming convention: request_TestSuiteName_TestCaseName_TestStepName.txt
def requestFile=subfolderPath1+"/request_"+testSuite+"_"+testCase+"_"+testStepName+".txt";
def rqfile = new File(requestFile);
rqfile.write(extRequest, "UTF-8");
// Extract the response from the test step
def extResponse = stepResult.getResponseContent();
// Create a file in the reports folder and write the response
// Naming convention: response_TestSuiteName_TestCaseName_TestStepName.txt
def responseFile=subfolderPath1+"/response_"+testSuite+"_"+testCase+"_"+testStepName+".txt";
def rsfile = new File(responseFile);
rsfile.write(extResponse, "UTF-8");
}
}
}
catch(exc)
{
log.error("Exception happened: " + exc.toString());
}
I would expect the output to be a json file, but it is a .csv one.
Edit:
TearDown script follows:
// Code to execute the GenerateJSONReport test step
testRunner.testCase.testSuite.project.testSuites["Library"].testCases["Reporting_Utility"].
testSteps["GenerateJSONReport"].run(testRunner, context);

groovy script not working in nifi executescript processor

I'm trying to execute something via executescript processor; a groovy code inside. In the code I'm trying to create a scala script which is to be executed on spark in a further processor.
// Get flow file
def flowFile = session.get()
if (!flowFile) return
// Create output directory
def userInputDir = flowFile.getAttribute("user.input.path")
def finalFolder = new File(userInputDir + "/" + innerDir)
try
{
if (!finalFolder.exists()) finalFolder.mkdirs()
// Write script
file = "spark.sqlContext.setConf(\"hive.exec.dynamic.partition\", \"true\")\n"
file = file + "spark.sqlContext.setConf(\"hive.exec.dynamic.partition.mode\", \"nonstrict\")\n"
file = file + "import org.apache.spark.sql._"
file = file + "\n"
file = file + "import java.io._"
file = file + "\n"
}
.
.
.
The rest other steps are adding some other spark specific commands to the script variable. Script is huge so skipping the full code paste.
Finally, closing with a catch
// Output file path
flowFile = session.putAttribute(flowFile, "generatedScript", scalaFile.getCanonicalPath())
session.transfer(flowFile, REL_SUCCESS)
}
catch(Exception e)
{
log.info("File: {}\n", finalFolder.file)
session.transfer(flowFile, REL_FAILURE)
}
The processor is not even beginning to start the groovy script execution and it fails with the error:
groovy.lang.MissingPropertyException: No such property: script for calss: javal.io.File
By the statement 'not even beginning to start' means that the previous queue is not empty and the processor throws the error. I'm guessing it's a syntax issue but I don't find any syntactical problems related in the script. I also tried running the script in local machine's groovy shell and have the same error there as well, but no syntax issue.
Googling the error got me the suggestion to include the imports in the script but even after including the relevant imports the error is the same.
Any clues?
You're referring to a variable "innerDir" which is not defined anywhere. Are you expecting the user to add a user-defined property to ExecuteScript called innerDir? If so, the innerDir variable in the script is a PropertyValue object, so you'd need to call getValue() on it to get the actual value of the property:
innerDir.value
Also you refer to scalaFile.getCanonicalPath() but scalaFile is not defined above, and getCanonicalPath() won't give you the contents of the script, is that what you meant?
I reworked the partial script above to assume that innerDir is a user-defined property and you write the contents of the file variable to a File pointed to by scalaFile; also I made it more Groovy by using heredoc instead of appending to the file variable:
// Get flow file
def flowFile = session.get()
if (!flowFile) return
// Create output directory
def userInputDir = flowFile.getAttribute("user.input.path")
def finalFolder = new File(userInputDir + "/" + innerDir?.value ?: '')
try
{
if (!finalFolder.exists()) finalFolder.mkdirs()
// Write script
file =
"""
spark.sqlContext.setConf("hive.exec.dynamic.partition", "true")
spark.sqlContext.setConf("hive.exec.dynamic.partition.mode", "nonstrict")
import org.apache.spark.sql._
import java.io._
"""
scalaFile = new File(finalFolder, 'script.scala')
scalaFile.withWriter {w -> w.write(file)}
// Output file path
flowFile = session.putAttribute(flowFile, "generatedScript", scalaFile.canonicalPath)
session.transfer(flowFile, REL_SUCCESS)
}
catch(Exception e) {
log.info("File: {}\n", finalFolder.file)
session.transfer(flowFile, REL_FAILURE)
}

SOAPUI Assertion script writing twice to file

I am writing a groovy script where I am extracting text from a response and writing it to an output file on my system. The problem I encounter is when I run the groovy script that calls the test. The script assertions runs and logs the text twice to the file.
It seems to write to the file just before it leaves the assertion.
I have tried the following:
...
...
if (context.alreadyWritten == null || !context.alreadyWritten) {
inputFile.append (testString+ "\n")
log.info testString
} else {
log.info ('Already written!')
}
I have set the flag (context.alreadyWritten) to false in groovy before I execute the test step.
SOAPUI version : 5.3.0
I see there was an issue previous with Smartbear when appending to file in an assertion script. However the workaround was advised to resolve this:
if (context.alreadyWritten == null || !context.alreadyWritten) {
}
Which does not resolve my issue
When I log the result using log.info I see only one instance of the message been logged.
Any ideas.
Thanks
If you are using Script Assertion, try below:
//Define the file name, change as needed
def fileName = '/path/to/file.xml'
//check if you got the response
if (context.response) {
log.info 'Response available and not empty'
def file = new File(fileName)
if (!context?.alreadySaved) {
file.write(context.response)
context.alreadySaved = true
log.info 'response written to file'
} else {
log.info 'Response already written'
}
} else {
log.info 'there is no response to save'
}

Automatically downloading Groovy console logs from Soap UI

I have Soap UI Pro. I am able to download all the system generated reports. I have a groovy script as one of the test steps and I am writing some transaction logs using log.info(). When I execute my test suite, I also want my console logs to be automatically downloaded to my machine. Can someone let me know if this is possible ?
or can I write my log.info() values to the system generated logs ?
There is my script to save the Script log to a file.
def loggerSize = 0
log.info "first log"
log.info "second log"
def logArea = null
logArea = com.eviware.soapui.SoapUI.logMonitor.getLogArea( "Script log" ); // Or HHTP log, Jetty log, Script log; each tab name in log part, can't capture 'Log Output' part ...
def model = null
def logger = ""
if( logArea != null ){
model = logArea.model
if( model.size > loggerSize ){
for(c in loggerSize..(model.size-1)){
logger += model.getElementAt(c).toString() + "##"
}
}
}
return logger

Write to file via jenkins post-groovy script on slave

I'd like to do something very simple: Create/write to a file located in the remote workspace of a slave via the jenkins groovy post-build script plug-in
def props_file = new File(manager.build.workspace.getRemote() + "/temp/module.properties")
def build_num = manager.build.buildVariables.get("MODULE_BUILD_NUMBER").toInteger()
def build_props = new Properties()
build_props["build.number"] = build_num
props_file.withOutputStream { p ->
build_props.store(p, null)
}
The last line fails, as the file doesn't exist. I'm thinking it has something to do with the output stream pointing to the master executor, rather than the remote workspace, but I'm not sure:
Groovy script failed:
java.io.FileNotFoundException: /views/build_view/temp/module.properties (No such file or directory)
Am I not writing to the file correctly?
While writing onto slave you need to check the channel first and then you can successfully create a file handle and start reading or writing to that file:
if(manager.build.workspace.isRemote())
{
channel = manager.build.workspace.channel;
}
fp = new hudson.FilePath(channel, manager.build.workspace.toString() + "\\test.properties")
if(fp != null)
{
String str = "test";
fp.write(str, null); //writing to file
versionString = fp.readToString(); //reading from file
}
hope this helps!
Search for words The post build plugin runs on the manager and doing it as you say will fail if you are working with slaves! on the plugin page (the link to which you've provided) and see if the workaround there helps.
Does the folder /views/build_view/temp exist?
If not, you will need to do new File( "${manager.build.workspace.remote}/temp" ).mkdirs()

Resources