1

Is there an easy way to append additional output to the default assertion failures?

I am able to over ride the output entirely with pytest_assertrepr_compare but i can't seem to get the default output and add my custom message to it.

Heres what i have tried:

from _pytest.assertion.util import assertrepr_compare
def pytest_assertrepr_compare(config, op, left, right):
    # append log output to normal compare
    pytest_output = assertrepr_compare(config, op, left, right)
    return pytest_output + ['THIS IS MY CUSTOM MESSAGE']

The assertrepr_compare doesn't return anything in this example. Any thoughts on how to achieve this?

jdennison
  • 2,000
  • 2
  • 15
  • 22
  • I believe this is a [duplicate](http://stackoverflow.com/questions/3807694/how-to-change-the-message-in-a-python-assertionerror) – T.Woody Oct 29 '14 at 00:17
  • I want to globally change the output for py.test and not on each individual assertion. – jdennison Oct 29 '14 at 00:21
  • I still think appending the `e.args` would work. I can run through some test cases, if that is not the case. – T.Woody Oct 29 '14 at 00:27
  • I just tried the approach of importing `assertrepr_compare` from `_pytest.assertion.util` and it works for me (pytest 4.4.0). Maybe this has changed in the meantime. – Ignitor Sep 20 '19 at 06:25

2 Answers2

0

When the pytest_assertrepr_compare() returns None it means there is no customisation happening. This means if you tried your example with something which would trigger detailed explanation in _pytest.assertion.util.assertrepr_compare it would work, e.g. assert 'foo' == 'bar'.

Unfortunately you can't have this additional to the explanation created by the re-writing module.

There already does exist some mechanism internally however, e.g. when you write assert 1 == 2, 'custom note' you will get the desired effect, but it's not global.

So I believe there is scope to improve customising reporting even more and it seems a few use-cases have recently been coming up. Could you describe this use-case in a new issue on the tracker please?

flub
  • 5,953
  • 27
  • 24
0

I was able to achieve this by attaching a failure info string to the config argument of pytest_assertrepr_compare:

def pytest_assertrepr_compare(config, op, left, right):
    if hasattr(config, "failure_info") and config.failure_info != None:
        print "Appended Failure Info:"
        print config.failure_info
        # Set to None to avoid the same failure_info for other tests
        config.failure_info = None

    # return None to trigger the default behavior 
    return None

Back in the test I would do something like:

def test_something(request):
    request.config.failInfo = 'THIS IS MY CUSTOM MESSAGE'
    assert 1 == 2

Since captured stdout/stderr is always printed for failing tests, you don't have to worry about your failure_info ever not being printed.

Hope this helps!

Dot.Bot
  • 11
  • 2