How to Remove Logging Output from Allure 2 - spock

I have Java/Groovy/Spock tests and Allure 2 report. I use allure.Step() annotation to describe all steps that I want to see in Allure report. For example:
def "some test"() {
when: "do some request"
Request.getRequest()
}
class Request {
#Step("GET https://some.request")
static Response getRequest() {
return given().log().all()
.filter(new AllureRestAssured())
.when()
.get(conf.url())
}
}
In that case I see two basically same blocks in report:
one beautiful block step with finely formatted request and response due to AllureRestAssured()
one ugly block with the same unformatted request and response info due to .log().all() console output.
Is there a way to remove all console output from Allure report and leave only methods that have #Step annotation?

Related

Use generic-webhook-trigger and pass JSON body as is instead of individual variables

I am using generic-webhook-trigger in Jenkins to trigger job when events happen in Github.
It seems I have to extract each variable I need from the big JSON request body to convert them to env-var.
Is it possible to pass the whole JSON body to the Jenkins job and have it parse it?
You can achieve what you want by assigning the entire body to a specific variable, then read it as Json in your code and parse it by yourself.
For example, if your payload (received post content) is:
{
"ref": "refs/heads/master",
"head_commit": {
"committer": {
"name": "ido",
"email": "ido#test.com"
}
}
}
You can define a single parameter in your generic webhook configuration called payload, set the expression for that parameter to $, set the expressionType JSONPath, and when the job is triggered that parameter will include the entire content of the received post content.
You can then parse it by yourself:
def payloadMap = readJSON text: payload
println "ref value is: ${payloadMap.ref}"
println "committer name is: ${payloadMap.head_commit.committer.name}"
You can see more advanced examples for using the generic-webhook-trigger configurations plugin Here, and especially This one which is more relevant for your requirements.

How to check the status of the sent email when using emailext plugin

I'm using the email Extension plugin for Jenkins 2.332.3 but when I get errors with the configuration of the email Extension my build still goes successful even if I get for example
AuthenticationFailedException message: 535 5.7.3 Authentication unsuccessful
Is there a way to get build failure if I have incorrect configurations of emailext?
My stage:
emailext(
attachmentsPattern: "test.txt",
subject: "Test",
body: "Example test",
replyTo: 'test#test.com'
)
When I have configurations valid I get
DEBUG SMTP: message successfully delivered to mail server
I briefly checked the source code of the plugin and this doesn't seem doable. All the errors are caught and handled gracefully. Check here. Also, the execution of the plugin doesn't even return a status code. Check here.
So AFAIU I don't see a way to know whether the email was sent.
Update
After thoroughly checking the code I observed that there is an option to execute a postscript after sending a mail. This script can be specified globally or within the pipeline. So I came up with a very hacky solution with some groovy. Basically, after sending the mail you can capture the response from the SMTP server. This response will have some details you can use to determine whether it's a success or a failure.
On success, you will see a response like the one below.(I used Gmail SMTP server here)
250 2.0.0 OK 1655253667 cc23-20020a05622a411700b00304f98ad3c1sm7772402qtb.29 - gsmtp
On Authentication failure, you should see something like the below.
535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials q18-20020a05622a04d200b002f906fc8530sm8752555qtx.46 - gsmtp
As I mentioned earlier the pipeline simply swallows all the errors that are thrown and from the script, there is no way to access the current build context. Hence as a workaround, I wrote the response to a file and then marked the status of the Job based on this. Please refer to the following pipeline.
pipeline {
agent any
stages {
stage('MailAndFail') {
steps {
script{
echo "Starting Mailing"
def script = "String response = transport.getLastServerResponse();println \"Mail Response: \" + response;File file = new File(\"/var/jenkins_home/workspace/EMAIEXT2222/MailResponse.txt\");file.write response"
emailext(
to: "test#gmail.com",
subject: "Test",
body: "Example test",
replyTo: 'test#test.com',
postsendScript: "$script"
)
sh "cat MailResponse.txt"
def response = readFile(file: 'MailResponse.txt')
if(!response.contains("2.0.0 OK")) {
echo "BUILD FAILURE!!!!"
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
Note: Make sure you change the file write path to a directory in the workspace /var/jenkins_home/workspace/EMAIEXT2222. Also, the print statements in the script will not be shown in the build console. You can see them in the Jenkins log. Also, make sure you approve the groovy script if you get an error that says the script doesn't have permission to execute. You can do this from here: http://JENKINSHOST/scriptApproval/

How to use ${currentBuild.result} to indicate "SUCCESS" not "null"

My Jenkins declarative pipeline has the following post action:
mail to: '<snip>',
subject: "Status of pipeline: ${currentBuild.fullDisplayName}",
body: "${env.BUILD_URL} has result ${currentBuild.result}"
When the build succeeds the content of the email body is:
<job name> has result null
I understand that the value of ${currentBuild.result}" is null when the job succeeds, but this isn't convenient for the user. What is the recommended way of printing "SUCCESS" (or "FAILURE" etc) in the body message?
Use ${currentBuild.currentResult} instead.
currentResult
typically SUCCESS, UNSTABLE, or FAILURE. Will never be null.
The syntax of the available global variables is available at ${YOUR_JENKINS_URL}/pipeline-syntax/globals. See more info about globals in Jenkins documentation.
Also see https://issues.jenkins.io/browse/WEBSITE-364
You can add mail step inside post step in pipeline as below :
pipeline {
agent any
stages {
stage('Example Test') {
steps {
echo 'Hello, JDK'
}
}
}
post {
success {
echo "${env.BUILD_URL} has result success"
}
failure {
echo "${env.BUILD_URL} has result fail"
}
}
}
CurrentBuild contains the following property. You can use them according to your need.
_class,
actions,
artifacts,
building,
description,
displayName,
duration,
estimatedDuration,
executor,
fullDisplayName,
id,
keepLog,
number,
queueId,
result,
timestamp,
URL,
changeSets,
culprits,
nextBuild,
previousBuild,
number

How to know which user answered a Jenkins-Pipeline input step?

I have a Jenkinsfile script that tests for the possibility to perform an SVN merge and then asks the user for the permission to commit the merge.
I would like to know the username that answers the "input" step in order to write it into the commit message.
Is this possibile?
This is what hypothetically I would like to do:
outcome = input message: 'Merge trunk into branch?', ok: 'Merge'
echo "User that allowed merge: ${outcome.user}"
The input step got an optional submitterParameter, which allows to specify the key of the returned Map that should contain the user who's submitting the input dialog:
If specified, this is the name of the return value that will contain the ID of the user that approves this input.
The return value will be handled in a fashion similar to the parameters value.
Type: String
This looks then as follows:
def feedback = input(submitterParameter: 'submitter', ...)
echo "It was ${feedback.submitter} who submitted the dialog."
P.S: If anybody is interested in a full-fledged code snippet returning the user both for positive and negative feedback to the dialog (and timeout as well), I kindly point to our pipeline library.
It is not currently possible, for now only entry parameters are returned in the input step answer, as mentionned in source code :
// TODO: perhaps we should return a different object to allow the workflow to look up
// who approved it, etc?
switch (mapResult.size()) {
case 0:
return null; // no value if there's no parameter
case 1:
return mapResult.values().iterator().next();
default:
return mapResult;
}
If you'd like to restrict which user(s) can approve the input step, you can however use the submitter parameter, e.g. :
input message: 'Approve ?', submitter: 'authorized-submitter'
EDIT
Since January 2017 it is now possible to request additional parameters to be sent. Please see StephenKing answer above.
If you are not asking for any parameters on the input, then adding the submitterParameter kind of worked. It didn't add it as a parameter on the return object, instead, it turned the returned object into a string with the username in it.
def feedback = input(submitterParameter: 'submitter')
echo "It was ${feedback} who submitted the dialog."
You can do this for exceptions if you turn off the groovy-sandbox:
try {
'Deploy to production?'
node {
sh 'echo deploying'
}
} catch(e) {
def user = e.getCauses()[0].getUser()
echo "Production deployment aborted by:\n ${user}"
}

Grails executor - can't use OauthService asynchronously

I installed the grails executor plugin so I can run some background task that takes a while to execute. The task requires that I call LinkedIn APIs using OauthService. The problem is that I can't seem to be able to call OauthService.accessResource in the asynchronous block, while the exact same code executes fine otherwise. Here's the code, simplified to illustrate the problem :
import org.grails.plugins.oauth.OauthService
class DemoController {
OauthService oauthService
def demo() {
runAsync {
println "ASYNC BEGIN"
def baseURL = "http://api.linkedin.com/v1/people-search?keywords=blah"
def async_response = oauthService.accessResource( baseURL, 'linkedin', [key:session.oauthToken.key, secret:session.oauthToken.secret], 'GET')
println "ASYNC END"
}
println "SYNC BEGIN"
def baseURL = "http://api.linkedin.com/v1/people-search?keywords=blah"
def sync_response = oauthService.accessResource( baseURL, 'linkedin', [key:session.oauthToken.key, secret:session.oauthToken.secret], 'GET')
println "SYNC END"
}
}
Here's the output :
SYNC BEGIN
2012-01-12 14:55:07,163 ["http-bio-8080"-exec-10] DEBUG oauth.OauthService - Attempting to access protected resource
2012-01-12 14:55:07,163 ["http-bio-8080"-exec-10] DEBUG oauth.OauthService - Executing GET to http://api.linkedin.com/v1/people-search?keywords=blah
ASYNC BEGIN
2012-01-12 14:55:07,780 ["http-bio-8080"-exec-10] DEBUG oauth.OauthService - Reading response body
2012-01-12 14:55:07,781 ["http-bio-8080"-exec-10] DEBUG oauth.OauthService - Response body read successfully
SYNC END
The asynchronous process just seems to stall on oauthService.accessResource and nothing gets executed after that. I get no other output ...
Any ideas ?
Thanks for your help.
(BTW I'm using grails 2.0, groovy 1.8.5)

Resources