vecin
vecin

Reputation: 563

Python pytest does not show assertion differences

The following test:

def test_something():
    assert "ddd" == "pepe"

When run with pytest gives this error message:

E       AssertionError: assert 'ddd' == 'pepe'
E         - ddd
E         + pepe

However if we move the assert method to a different file assertion.py:

class CustomerAssertor(object):
    def __init__(self,name):
        self.name =name

    def assert_name(self,expected):
        assert self.name ==expected

And we change the test to:

from sql_gen.test.utils.assertion_util import CustomerAssertor

def test_something():
    CustomerAssertor("ddd").assert_name("pepe")

Now I get the following error:

self = <assertions.CustomerAssertor object at 0x7fbcc3d31588>, expected = 'pepe'

    def assert_name(self,expected):
>       assert self.name ==expected
E       AssertionError

This message is not as informative as it doesn't tell you what the name's value is, why?

Upvotes: 11

Views: 3478

Answers (1)

user2357112
user2357112

Reputation: 281988

From the docs:

Reporting details about a failing assertion is achieved by rewriting assert statements before they are run. Rewritten assert statements put introspection information into the assertion failure message. pytest only rewrites test modules directly discovered by its test collection process, so asserts in supporting modules which are not themselves test modules will not be rewritten.

You can manually enable assertion rewriting for an imported module by calling register_assert_rewrite before you import it (a good place to do that is in conftest.py).

Upvotes: 17

Related Questions