Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert JSON equality in python-behave with diffs on failing tests?

How do I assert JSON equality in python-behave and get a diff as output when assertion fails?

In Ruby I use: https://github.com/collectiveidea/json_spec , so I am basically looking for similar functionality in Python.

With a normal assert statement the output is very unhelpful.

like image 641
Erik Avatar asked Mar 03 '26 06:03

Erik


1 Answers

I needed a similar functionality a while back. The easiest way I found was to use https://github.com/ChannelIQ/jsoncompare. You can install it with:

$ pip install jsoncompare

Then in your step code you can make an assert like this:

from jsoncompare import jsoncompare

if jsoncompare.are_same(json1, json2):
    assert True
else:
    print (jsoncompare.are_same(json1, json2))
    assert False 

By default, behave does not display print statements unless there is a failure, you must make the test fail in order to get the diff output to display.

like image 168
accraze Avatar answered Mar 05 '26 05:03

accraze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!