Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
vecin Avatar asked Feb 20 '19 22:02

vecin


1 Answers

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).

like image 62
user2357112 supports Monica Avatar answered Oct 22 '22 18:10

user2357112 supports Monica