pythonpytestassertautotest

How to get detailed assertion error messages from an external assertion function in pytest?


I'm trying to move assert statements out of my test function into a separate function when using pytest. Here is an example:

def assertions():
    assert 1 + 1 == 2, 'Addition error'
    assert 2 * 2 == 4, 'Multiplication error'
    assert 3 - 1 == 2, 'Subtraction error'
    assert 4 / 2 == 2, 'Division error'
    assert 5 % 2 == 1, 'Modulo error'
    assert 2 * 2 == 5, 'Multiplication error with wrong value'  # This will fail

def test_example():
    assertions()

When I run this, the assertion assert 2 * 2 == 5 fails as expected, but the pytest output does not include the custom error message ('Multiplication error with wrong value'). Instead, the output looks like this:

test_demo.py::test_example FAILED                                       [100%]
test_demo.py:16 (test_example)
4 != 5

Expected :5
Actual   :4

<Click to see difference>

def test_example():
       assertions()

test_demo.py:19:

============================== 1 failed in 0.25s ===============================

There is no information about the custom error message, and the output doesn't specify the exact line in the assertions() function where the failure occurred. It only shows the line where assertions() is called within test_example().

Is there a way to configure pytest to provide the same detailed output for assertions within an external function as it does for assertions directly inside the test function?


Solution

  • There is nothing wrong with your code. It is working as expected. This is the output it is providing