pytest truncates assert message, when message is a list/dict of long strings

Viewed 207

The assert keyword in python takes an expression, and an optional message to display. The message is useful when running pytest.

assert False, 'My message'

In addition to strings, you can raise any object, for example a dict or list.

However, pytest will truncate it if the message is a list with long strings:

def test():
    assert False, ['a' * 1000, 'a' * 1000, 'a' * 1000]

Pytest will show this which is confusing, because it appears like one item in the list instead of three:

    def test():
>       assert False, ['a' * 1000, 'a' * 1000, 'a' * 1000]
E       AssertionError: ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa']
E       assert False

How can I prevent pytest from truncating the assert message if the message is a list/dict with long strings?

The same is true for dictionaries, pytest makes it look like there is only one item in the dictionary, not three:

def test():
    assert False, {'foo': 'a' * 1000, 'bar': 'a' * 1000, 'baz': 'a' * 1000}
    def test():
>       assert False, {'foo': 'a' * 1000, 'bar': 'a' * 1000, 'baz': 'a' * 1000}
E       AssertionError: {'bar': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'}
E       assert False

The interesting thing is that if you convert it to a string it will not truncate the string:

def test():
    assert False, '\n'.join(['a' * 1000, 'a' * 1000, 'a' * 1000])

I don't want to have to remember to do this everytime I am returning a list of long strings.

1 Answers

pytest rewrites all the assertions it finds in the source code unless you explicitly disable this behaviour. To disable with

pytest test.py --assert=plain

Or by writing it in the module docstring

"""module xyz
PYTEST_DONT_REWRITE
"""

You can find here the documentation and, if you are interested, here the implementation of the visitor that rewrites all the assert statement.

Related