I'm trying to let a script assertion fail, when a variable has another value than defined. My goal: Mark the TestStep as red, if the TestStep will fail. Please note that I am using a script assertion for a TestStep - not a separate Groovy-Script TestStep.
My script looks like this:
httpResponseHeader = messageExchange.responseHeaders
contentType = httpResponseHeader["Content-Type"]
log.info("Content-Type: " + contentType)
if (contentType != "[image/jpeg]"){
log.info("ERROR! Response is not an image.")
//Script Assertion should fail.
//TestStep should be marked red.
} else {
log.info("OK! ResponseType is an image.")
}
Is there any way, how to let the script assertion fail depending on a property?
I've tried to use the getStatus() method, but this is only available for the testrunner object. Unfortunately the testRunner-object can not be used within a script assertion concerning this post: http://forum.soapui.org/viewtopic.php?f=2&t=2494#p9107
Need to assert so that test fails or passes automatically based on the condition.
def httpResponseHeader = messageExchange.responseHeaders
def contentType = httpResponseHeader["Content-Type"]
log.info("Content-Type: " + contentType)
assert contentType.get(0) == "image/jpeg","Content Type is not an image"
EDIT: Earlier paid attention to how to throw error, assuming you have the rest in place. Now changed last line of code based on the input.
Related
I want to write a code for Response assertion using groovy script , for the Response data like this:
[
{
"fieldId":"947bb60f",
"id":"e7b8ad2b",
"name":"field",
}
]
Tried using the below groovy script for which i am getting error(failure message).
if (!jsonResponse.keySet().containsAll(["fieldId","id","name"] )) {
failureMessage += "The json response body has wrong structure or error msg.\n\n";
}
The same script working fine with the single tree structure as below. Appreciate your help on this with groovy script .
[
"fieldId":"947bb60f",
"id":"e7b8ad2b",
"name":"field",
]
So, you are getting a list of items returned (containing a single item)
Assuming you never expect more than one item, you can check the size of it with:
if (jsonResponse.size() != 1) {
failureMessage += "Expected one item, got ${jsonResponse.size()}.\n\n";
}
Then, you can grab the first element with:
def jsonElement = jsonResponse[0]
And check the field names with:
if (jsonElement.keySet() != ["fieldId","id","name"] as Set) {
failureMessage += "Unexpected fields in response ${jsonElement.keySet()}.\n\n";
}
Please don't hate me, yes I want to do something really stupid.
I want to get null on every attribute if it does not exist. I found out that I can create the propertyMissing method:
class User {
String name = "A"
}
Object.metaClass.propertyMissing() {
null
}
u = new User();
println u?.name
println u?.namee
This prints:
A
null
Now I have the "great" Hybris system in my back :D
If I add the propertyMissing part on top of my script and run this in the Hybris groovy console, I still get the MissingPropertyException.
Is there another way to avoid the MissingPropertyException exception without having to work with hundreds of try catch? (or hundreds of println u?.namee ? u.namee : null isn't working)
/Edit: 1
I have the following use case (for the Hybris system):
I want to get all necessary information in a dynamic output from some pages. Why dynamic? Some page components have the attribute headline other teaserHeadline and some other title. To avoid to create each time an try catch or if else, I created a function which loops through possible attributes and if it's null it skips that one. For that I need to return null on attributes which doesn't exist.
Here is an example which should work, but it doesn't (don't run it on your live system):
import de.hybris.platform.servicelayer.search.FlexibleSearchQuery;
import de.hybris.platform.servicelayer.search.SearchResult;
flexibleSearch = spring.getBean("flexibleSearchService")
FlexibleSearchQuery query = new FlexibleSearchQuery("select {pk} from {ContentPage}");
SearchResult searchResult = flexibleSearch.search(query);
def i = 0;
def max = 1;
searchResult.result.each { page ->
if (i < max) {
gatherCMSPageInformation(page)
}
i++;
}
def gatherCMSPageInformation(page) {
page.class.metaClass.propertyMissing() {
null
}
println page.title2
}
Weird thing is, that if I run it a few times in a small interval, it starts to work. But I can't overwrite "null" to something else like "a". Also I noticed, to overwrite the Object class isn't working at all in Hybris.
/Edit 2:
I noticed, that I'm fighting against the groovy cache. Just try the first example, change null with a and then try to change it again to b in the same context, without restarting the system.
Is there a way to clear the cache?
why don't you use the groovy elvis operator?
println u?.namee ?: null
I have suite to run the regression Test Case in Soap UI. It has a Assertion Capture Response which measures the time of each request. This is needed on demand.
If metrics needed then I need to Enable the Capture Response Time assertion and if it is not needed then I don't need the capture response time.
I have written the below code to check that whether it is disabled or not. If it is disabled then OK else i need to disable it.
The following code returns
java.lang.NullPointerException: Cannot get property 'disabled' on null object.
Can any one help on this?
def project = testRunner.getTestCase().getTestSuite().getProject().getWorkspace().getProjectByName("Regression");
//Loop through each Test Suite in the project
for(suite in project.getTestSuiteList())
{
//log.info(suite.name)
//Loop through each Test Case
if(suite.name == "ReusableComponent")
{
for(tcase in suite.getTestCaseList())
{
log.info(tcase.name)
for(tstep in tcase.getTestStepList())
{
stepName = tstep.name
suiteName=suite.name
caseName=tcase.name
def testStep = testRunner.testCase.testSuite.project.testSuites["$suiteName"].testCases["$caseName"].getTestStepByName("$stepName")
log.info(testStep.getAssertionByName("CaptureResponseTime").disabled)
}
}
}
}
Below statement is causing NullPointerException:
log.info(testStep.getAssertionByName("CaptureResponseTime").disabled)
In order to avoid NPE, then change it to:
log.info(testStep.getAssertionByName("CaptureResponseTime").isDisabled)
If you need to disable the assertion, then use below statement:
testStep.getAssertionByName("CaptureResponseTime")?.disabled = true
Another input:
In order to get the project, do not use workspace.
Instead use:
def project = context.testCase.testSuite.project
I'm using a softassert in testNG from org.testng.asserts.SoftAssert
I'm testing something very basic - the title - just to see if I can get the soft assert to work and to put feedback in the report if it fails. Problem is, in either case where the assertion should pass or fail, it just always returns null.
#Test
void doTest()
{
driver.get("URL")
System.out.println(driver.getTitle())
l_assert.assertEquals(driver.getTitle(), "String")
l_assert.assertAll()
}
This always returns null
Probably the problem is that you didn't initialize it. You have to have this somewhere:
l_assert = new SoftAssert();
Try to use next example:
l_assert.assertEquals(driver.getTitle(), "String", "Error Message Should Be Here");
I have a parameterized job that uses the Perforce plugin and would like to retrieve the build parameters/properties as well as the p4.change property that's set by the Perforce plugin.
How do I retrieve these properties with the Jenkins Groovy API?
Update: Jenkins 2.x solution:
With Jenkins 2 pipeline dsl, you can directly access any parameter with the trivial syntax based on the params (Map) built-in:
echo " FOOBAR value: ${params.'FOOBAR'}"
The returned value will be a String or a boolean depending on the Parameter type itself. The syntax is the same for scripted or declarative syntax. More info at: https://jenkins.io/doc/book/pipeline/jenkinsfile/#handling-parameters
If your parameter name is itself in a variable:
def paramName = "FOOBAR"
def paramValue = params.get(paramName) // or: params."${paramName}"
echo """ FOOBAR value: ${paramValue}"
Original Answer for Jenkins 1.x:
For Jenkins 1.x, the syntax is based on the build.buildVariableResolver built-ins:
// ... or if you want the parameter by name ...
def hardcoded_param = "FOOBAR"
def resolver = build.buildVariableResolver
def hardcoded_param_value = resolver.resolve(hardcoded_param)
Please note the official Jenkins Wiki page covers this in more details as well, especially how to iterate upon the build parameters:
https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+System+Groovy+script
The salient part is reproduced below:
// get parameters
def parameters = build?.actions.find{ it instanceof ParametersAction }?.parameters
parameters.each {
println "parameter ${it.name}:"
println it.dump()
}
For resolving a single parameter (I guess what's most commonly needed), this is the simplest I found:
build.buildVariableResolver.resolve("myparameter")
in your Groovy System script build step.
Regarding parameters:
See this answer first. To get a list of all the builds for a project (obtained as per that answer):
project.builds
When you find your particular build, you need to get all actions of type ParametersAction with build.getActions(hudson.model.ParametersAction). You then query the returned object for your specific parameters.
Regarding p4.change: I suspect that it is also stored as an action. In Jenkins Groovy console get all actions for a build that contains p4.change and examine them - it will give you an idea what to look for in your code.
I've just got this working, so specifically, using the Groovy Postbuild plugin, you can do the following:
def paramText
def actionList = manager.build.getActions(hudson.model.ParametersAction)
if (actionList.size() != 0)
{
def pA = actionList.get(0)
paramText = pA.createVariableResolver(manager.build).resolve("MY_PARAM_NAME")
}
In cases when a parameter name cannot be hardcoded I found this would be the simplest and best way to access parameters:
def myParam = env.getProperty(dynamicParamName)
In cases, when a parameter name is known and can be hardcoded the following 3 lines are equivalent:
def myParam = env.getProperty("myParamName")
def myParam = env.myParamName
def myParam = myParamName
To get the parameterized build params from the current build from your GroovyScript (using Pipeline), all you need to do is:
Say you had a variable called VARNAME.
def myVariable = env.VARNAME
Get all of the parameters:
System.getenv().each{
println it
}
Or more sophisticated:
def myvariables = getBinding().getVariables()
for (v in myvariables) {
echo "${v} " + myvariables.get(v)
}
You will need to disable "Use Groovy Sandbox" for both.
If you are trying to get all parameters passed to Jenkins job you can use the global variable params in your groovy pipeline to fetch it.
http://jenkins_host:8080/pipeline-syntax/globals
params
Use something like below.
def dumpParameter()
{
params.each {
println it.key + " = " + it.value
}
}
thanks patrice-n! this code worked to get both queued and running jobs and their parameters:
import hudson.model.Job
import hudson.model.ParametersAction
import hudson.model.Queue
import jenkins.model.Jenkins
println("================================================")
for (Job job : Jenkins.instanceOrNull.getAllItems(Job.class)) {
if (job.isInQueue()) {
println("------------------------------------------------")
println("InQueue " + job.name)
Queue.Item queue = job.getQueueItem()
if (queue != null) {
println(queue.params)
}
}
if (job.isBuilding()) {
println("------------------------------------------------")
println("Building " + job.name)
def build = job.getBuilds().getLastBuild()
def parameters = build?.getAllActions().find{ it instanceof ParametersAction }?.parameters
parameters.each {
def dump = it.dump()
println "parameter ${it.name}: ${dump}"
}
}
}
println("================================================")
The following can be used to retreive an environment parameter:
println System.getenv("MY_PARAM")
The following snippet worked for me to get a parameter value in a parameterized project:
String myParameter = this.getProperty('binding').getVariable('MY_PARAMETER')
The goal was to dynamically lock a resource based on the selected project parameter.
In "[✓] This build requires lockable resources" I have the following "[✓] Groovy Expression":
if (resourceName == 'resource_lock_name') {
Binding binding = this.getProperty('binding')
String profile = binding.getVariable('BUILD_PROFILE')
return profile == '-Poradb' // acquire lock if "oradb" profile is selected
}
return false
In "[✓] This project is parameterized" section I have a "Choice Parameter" named e.g. BUILD_PROFILE
Example of Choices are:
-Poradb
-Ph2db
-DskipTests -T4
The lock on "resource_lock_name" will be acquired only if "-Poradb" is selected when building project with parameters
[-] Use Groovy Sandbox shall be unchecked for this syntax to work