Ask a Question

How to stop "assert" to display junk at the end of a failed assertion message?


How to stop "assert" to display junk at the end of a failed assertion message?

There is an annoying side effect when using "assert" in a groovy script to verify items from a property. It often displays too much junk at the end of it:


Assertion failed:

assert ep.Flow == sp.flow
| | | | |
| '0' | | 0.0
| | ['startDate':'2020-09-02T15:30:00', 'endDate':'2020-09-02T16:24:00', 'flow':0.0, 'flowUnit':['unit':'', 'flowTimeUnit':'Unspecified', 'version':'2.5.0'], .
| false

error at line: 10


If however the value is first copied into another variable, then it displays correctly.


        def f = sp.flow
        assert ep.Flow == f; 



Assertion failed: 

assert ep.Flow == f
       |  |    |  |
       |  '0'  |  0.0
       |       false

error at line: 10


However, this bloats the code unnecessarily.  Is there a better way to deal with it?  


Occasional Visitor

The easiest way to stop the display of junk at the end of a failed assertion message is to use the assert function from the built-in Python "unittest" library instead of the assert statement. The unittest library provides more control over the assertion messages and their formatting.  upsers account


Interesting.  Could you give an example or is there some documentation about how to do this? 

Champion Level 3


You can add your own message than default one using below approach.

assert condition, customMessage


def x = -5
assert x > 0, "x should be positive"


Not sure how this answers my question. The problem is that I try to avoid extra work to assert a variable having to do anything.  Groovy seems to be strange that it treats the original variable different when it is copied into another.  As you can see from the examples I have given, it is both times the exact same test.  The only difference that when I use the original variable for assert, it also displays a lot of junk after it, but when I copy it into another variable first and then do an assert, it doesn't.   I just wonder if there is something that can be done to stop this behaviour. 

Champion Level 3

There is little misread from my end. Thought you are saying the assert default message as junk and missed the main point.

The reason for assert failure is comparing different data types i.e., string vs decimal number.

Try to compare the data of same type, otherwise cast before compare.

Showing results for 
Search instead for 
Did you mean: