SoapUI write testsuite name to file - groovy

I want to print my test suite into file
def fileDir = new File("C:\\SoapUIResults");
if(!fileDir .exists()) {
fileDir .mkdirs();
} def myFile= new File(fileDir , "myFile.txt"); //If the file does not already exist, we want to create it, otherwise we want to append
if(!myFile.exists()) { myFile.createNewFile(); }
myFile.append(testRunner.testSuite.name +'\n' ); //Test suite Name

Your question is not clear for me, the only thing that I see wrong in your code is that you are missing testCase to access testSuite properties from testRunner, to do so you must use testRunner.testCase.testSuite.name instead of testRunner.testSuite.name.
If you are looking for a way to save all testSuite results on a file take a look on this answer
Hope this helps,

Related

Adding a method from an external groovy script with GroovyShell()

I have a groovy script (source.groovy) that needs to call a method from another groovy script (external.groovy). The problem is external.groovy imports a library that does not exists so I get an error. Here is an example:
Source.groovy:
new GroovyShell().parse( new File( 'external.groovy' ) ).with {
method()
}
Here is external.groovy:
import com.foo.doesnotexsist
def method() {println "test"}
When I run Source.groovy I get an error because com.foo.doesnotexsist does not exist. I don't care that it does not exists because it does not effect the method() function. Is there a way I can call the method() function?
Maybe it is not the way we want to achieve that, but there is simple solution to remove unwanted imports:
def text = new File( 'external.groovy' ).findAll{!(it =~ /^\s*import/)}.join('\n')
new GroovyShell().parse( text ).with{method()}

Reading file from Workspace in Jenkins with Groovy script

I want to add a Build step with the Groovy plugin to read a file and trigger a build fail depending on the content of the file.
How can I inject the workspace file path in the groovy plugin ?
myFileDirectory = // Get workspace filepath here ???
myFileName = "output.log"
myFile = new File(myFileDirectory + myFileName)
lastLine = myFile.readLines().get(myFile.readLines().size().toInteger() - 1)
if (lastLine ==~ /.Fatal Error.*/ ){
println "Fatal error found"
System.exit(1)
} else{
println "nothing to see here"
}
I realize this question was about creating a plugin, but since the new Jenkins 2 Pipeline builds use Groovy, I found myself here while trying to figure out how to read a file from a workspace in a Pipeline build. So maybe I can help someone like me out in the future.
Turns out it's very easy, there is a readfile step, and I should have rtfm:
env.WORKSPACE = pwd()
def version = readFile "${env.WORKSPACE}/version.txt"
If you are trying to read a file from the workspace during a pipeline build step, there's a method for that:
readFile('name-of-file.groovy')
For reference, see https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#readfile-read-file-from-workspace.
Based on your comments, you would be better off with Text-finder plugin.
It allows to search file(s), as well as console, for a regular expression and then set the build either unstable or failed if found.
As for the Groovy, you can use the following to access ${WORKSPACE} environment variable:
def workspace = manager.build.getEnvVars()["WORKSPACE"]
Although this question is only related to finding directory path ($WORKSPACE) however I had a requirement to read the file from workspace and parse it into JSON object to read sonar issues ( ignore minor/notes issues )
Might help someone, this is how I did it-
from readFile
jsonParse(readFile('xyz.json'))
and jsonParse method-
#NonCPS
def jsonParse(text) {
return new groovy.json.JsonSlurperClassic().parseText(text);
}
This will also require script approval in ManageJenkins-> In-process script approval
May this help to someone if they have the same requirement.
This will read a file that contains the Jenkins Job name and run them iteratively from one single job.
Please change below code accordingly in your Jenkins.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '
##To read file from workspace which will contain the Jenkins Job Name ###
def filePath = readFile "${WORKSPACE}/ Your File Location"
##To read file line by line ###
def lines = filePath.readLines()
##To iterate and run Jenkins Jobs one by one ####
for (line in lines) {
build(job: "$line/branchName",
parameters:
[string(name: 'vertical', value: "${params.vert}"),
string(name: 'environment', value: "${params.env}"),
string(name: 'branch', value: "${params.branch}"),
string(name: 'project', value: "${params.project}")
]
)
}
}
}
}
}
}
If you already have the Groovy (Postbuild) plugin installed, I think it's a valid desire to get this done with (generic) Groovy instead of installing a (specialized) plugin.
That said, you can get the workspace using manager.build.workspace.getRemote(). Don't forget to add File.separator between path and file name.
As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the
Extended Choice Parameter. Here is my solution with the printlns:
import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
try{
//get Jenkins instance
def jenkins = Jenkins.instance
//get job Item
def item = jenkins.getItemByFullName("The_JOB_NAME")
println item
// get workspacePath for the job Item
def workspacePath = jenkins.getWorkspaceFor (item)
println workspacePath
def file = new File(workspacePath.toString()+"\\pom.xml")
def pomFile = new XmlSlurper().parse(file)
def pomModules = pomFile.modules.children().join(",")
return pomModules
} catch (Exception ex){
println ex.message
}

Variable project configuration is bound to in groovy axis plugin for jenkins

I have a multi-configuration build for which I'd like essentally one build to be run for each file matching foo/*/bar/*.xml. I figured the GroovyAxis Plugin would be a nice fit, but I cannot find any documentation on how the build configuration can be accessed from within the script, so I cannot read the workspace-directory from anywhere.
Running something like return new File('.').listFiles().collect{it.toString()} returns all files within the root directory of the server.
Can anyone point me in the right direction?
It took a while to figure this out, but here is a solution. Note that since the Groovy script runs on the master, you must use FilePath to access the files on the slave.
import hudson.FilePath
def workspace = context?.build?.workspace
if (null == workspace) {
return ['noworkspace'] // avoid returning 'default' so the user has a chance of figuring out what went wrong
}
def configDir = workspace.toString() + '/openpower/configs/'
def dir = new FilePath(workspace.channel, configDir)
def files = []
dir.list().each {
def name = it.getName()
if (name.endsWith('_defconfig')) {
files << name.replace('_defconfig', '')
}
}
return files

groovy parse local html file

I am working on a groovy script that will get all the local html files and parse certain tags in them. I tried using something like html clean and it just is not working. I tried to read each line but that only works when the stuff I need is on 1 line. I have this script up on github, https://github.com/jrock2004/johns-octopress-scripts/blob/master/convertCompiledPosts/convertPosts.groovy. Thanks for any input
Edit: So I am getting closer. I have this code now
def parser = new org.cyberneko.html.parsers.SAXParser()
new XmlParser( parser ).parse( curFile+ "/index.html" ).with { page ->
page.'**'.DIV.grep { it.'#class'?.contains 'entry-content' }.each {
println it
println "--------------------------------"
}
}
And what it prints is
DIV[attributes={class=entry-content}; value=[P[attributes={}; value=[As an automation developer, I have learned how to write code in Java. When I am having an issue, one of the nice things that you can do is debug your code, line by line. For the longest I had wished that something like this existed in PHP. I have come to find out that you can actually debug code, like I do in Java. This is such a helpful task because I do not have to waste time using var_dump and such on variables or results. In your apache/php server you need to install and or enable something called, A[attributes={href=http://xdebug.org/}; value=[Xdebug]], . I will work on a tutorial on how to use xdebug while writing code in Sublime Text 2. So keep an eye out on my blog and or, A[attributes={href=http://www.youtube.com/jrock20041}; value=[YouTube]], channel for this tutorial.]]]]
So basically what I want is I wall the text including the html elements in the div with the class entry-content. If you want to see the page it can be found here -- http://jcwebconcepts.net/blog/2013/02/02/xdebug/
Thanks for your help
It does work... Save the HTML for this page to a file, then you can parse it.
The following code prints the name of the author of every comment on the page:
#Grab('net.sourceforge.nekohtml:nekohtml:1.9.16')
def parser = new org.cyberneko.html.parsers.SAXParser()
new XmlParser( parser ).parse( file ).with { page ->
page.'**'.A.grep { it.'#class'?.contains 'comment-user' }.each {
println it.text()
}
}
When file is set to be a File pointing to the saved HTML (or a String containing the URL of this question), it prints:
tim_yates
jrock2004
tim_yates
Edit:
To print the contents of a given node, you could do (using the example from your edited question):
#Grab('net.sourceforge.nekohtml:nekohtml:1.9.16')
import groovy.xml.*
def parser = new org.cyberneko.html.parsers.SAXParser()
new XmlParser( parser ).parse( 'http://jcwebconcepts.net/blog/2013/02/02/xdebug/' ).with { page ->
page.'**'.DIV.grep { it.'#class'?.contains 'entry-content' }.each { it ->
println XmlUtil.serialize( it )
}
}

How can I use relative paths to external response files for soapUI MockService

What I've Done
I am using soapUI (3.6.1 Free version) mock services to serve up specific data to 2 client applications I am testing. With some simple Groovy script I've set up some mock operations to fetch responses from specific files based on the requests made by the client applications.
The static contents of the mock response is:
${responsefile}
The groovy in the operation dispatch scripting pane is:
def req = new XmlSlurper().parseText(mockRequest.requestContent)
if (req =~ "CategoryA")
{
context.responsefile = new File("C:/soapProject/Test_Files/ID_List_CategoryA.xml").text
}
else
{
context.responsefile = new File("C:/soapProject/Test_Files/ID_List_CategoryB.xml").text
}
In this example, when the client application issues a request to the mock service that contains the string CategoryA, the response returned by soapUI is the contents of file ID_List_CategoryA.xml
What I'm Trying To Achieve
This all works fine with the absolute paths in the groovy. Now I want to pull the whole collection of soapUI project file and external files into a package for easy re-deployment. From my reading about soapUI I hoped this would be as easy as setting the project Resource Root value to ${projectDir} and changing my paths to:
def req = new XmlSlurper().parseText(mockRequest.requestContent)
if (req =~ "CategoryA")
{
context.responsefile = new File("Test_Files/ID_List_CategoryA.xml").text
}
else
{
context.responsefile = new File("Test_Files/ID_List_CategoryB.xml").text
}
... keeping in mind that the soapUI project xml file resides in C:/soapProject/
What I've Tried So Far
So, that doesn't work. I've tried variations of relative paths:
./Test_Files/ID_List_CategoryA.xml
/Test_Files/ID_List_CategoryA.xml
Test_Files/ID_List_CategoryA.xml
One post indicated that soapUI might consider the project files parent directory as the root for the purposes of the relative path, so tried the following variations too:
./soapProject/Test_Files/ID_List_CategoryA.xml
/soapProject/Test_Files/ID_List_CategoryA.xml
soapProject/Test_Files/ID_List_CategoryA.xml
When none of that worked I tried making use of the ${projectDir} property in the groovy script, but all such attempts failed with a "No such property: mockService for class: Script[n]" error. Admittefly, I was really fumbling around when trying to do that.
I tried using information from this post and others: How do I make soapUI attachment paths relative?
... without any luck. Replacing "test" with "mock," (among other changes), in the solution code from that post resulted in more property errors, e.g.
testFile = new File(mockRunner.project.getPath())
.. led to...
No such property: mockRunner for class: Script3
What I Think I Need
The posts I've found related to this issue all focus on soapUI TestSuites. I really need a solution that is MockService centric or at least sheds some light on how it can be handled differently for MockServices as opposed to TestSuites.
Any help is greatly appreciated. Thanks. Mark.
The Solution - Provided by GargantuChet
The following includes the changes suggested by GargantuChet to solve the problem of trying to access the ${projectDir} property and enable the use of relative paths by defining a new projectDir object within the scope of the groovy script:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def projectDir = groovyUtils.projectPath
def req = new XmlSlurper().parseText(mockRequest.requestContent)
if (req =~ "CategoryA")
{
context.responsefile = new File(projectDir, "Test_Files/ID_List_CategoryA.xml").text
}
else
{
context.responsefile = new File(projectDir, "Test_Files/ID_List_CategoryB.xml").text
}
I'm not familiar with Groovy, but I assume the File is a normal java.io.File instance.
Relative paths are interpreted as being relative to the application's current directory. Try something like the following to verify:
def defaultPathBase = new File( "." ).getCanonicalPath()
println "Current dir:" + defaultPathBase
If this is the case here, then you may want to use the new File(String parent, String child) constructor, passing your resource directory as the first argument and the relative path as the second.
For example:
// hardcoded for demonstration purposes
def pathbase = "/Users/chet"
def content = new File(pathbase, "Desktop/sample.txt").text
println content
Here's the result of executing the script:
Chets-MacBook-Pro:Desktop chet$ groovy sample.groovy
This is a sample text file.
It will be displayed by a Groovy script.
Chets-MacBook-Pro:Desktop chet$ groovy sample.groovy
This is a sample text file.
It will be displayed by a Groovy script.
Chets-MacBook-Pro:Desktop chet$
You could have also done the following to get the value of projectDir:
def projectDir = context.expand('${projectDir}');

Resources