Thursday, August 16, 2018

Why doesn't Groovy's power assert work in a Jenkins job

Leave a Comment

Power assertions work in the /script, but do not work in a Jenkinsfile driven job. Why? Is there a way to get it to work?

In Jenkinsfile job:

assert 1 == 2  at org.codehaus.groovy.runtime.InvokerHelper.assertFailed(InvokerHelper.java:404) ... wall of stack trace 

In /script window

Assertion failed:   assert 1 == 2          |          false 

In this trivial example, it is easy to figure out what is going on. In practice, one or both of the operands of "==" will be a variable. In the /script version, it will display the values (see the link above). In the Jenkinsfile console log you just get the assert statement as is with no hints.

Added after @daggett question:

node ()   {   stage('assert')     {     try        {       two = 2       assert 1==two        }     catch(Throwable t)       {       println t       error "assert failed"       }     }   } 

output:

Assertion failed:   assert 1==two 

2 Answers

Answers 1

Not possible as far as I can see. Jenkins pipeline groovy DSL uses custom CPS interpreter during interpretation of groovy. This means that it bypasses/overrides a lot of the standard implementation of groovy, and thus also the assert implementation. The assert implementation for Jenkins Pipeline CPS can be found here, while the real groovy implementation uses this class during the assert evaluation in order to record values and print proper exception.

In order to get similar behaviour in Jenkins pipeline CPS one would either need to refactor the groovy code base and Jenkins CPS code or duplicate a lot of the functionality in the AssertionWriter class linked above.

Answers 2

This is an example of a hack that sort of works:

def ASSERT_EQ (def arg1, def arg2)   {   if (arg1 != arg2)     {     println ('arg1 = ' + arg1 + " " + arg1.getClass())     println ('arg2 = ' + arg2 + " " + arg2.getClass())     }   assert arg1 == arg2   } 

It is not nearly as robust as the normal groovy power assert.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment