[pytest-dev] Failure to create representation with sets having "unsortable" elements

Edison Gustavo Muenz edisongustavo at gmail.com
Mon Apr 6 15:37:28 CEST 2015


Hello all,

I’m using Python 2.7.7 (The error also happens on Python 2.7.9)

The following code fails:

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

        def __lt__(self, other):
            raise RuntimeError()

        def __repr__(self):
            return self.name

        def __hash__(self):
            return hash(self.name)

        def __eq__(self, other):
            return self.name == other.name

    assert {UnsortableKey('1'), UnsortableKey('2')} == {UnsortableKey('2')}

>       assert {UnsortableKey('1'), UnsortableKey('2')} == {UnsortableKey('2')}
E       assert set([1, 2]) == set([2])
E         (pytest_assertion plugin: representation of details failed.
Probably an object has a faulty __repr__.)
E         X:\etk\coilib50\source\python\coilib50\_pytest\_tests\pytest_almost_equal.py:766:
RuntimeError

While debugging, the problem happens in this line
<https://github.com/python/cpython/blob/2.7/Lib/pprint.py#L199> of pprint.py
(The PrettyPrinter module).

It assumes that the “object” can have the method sorted() called on it,
which is not always true. The repr.py module handles this correctly, but
pprint.py doesn’t.

This is the full traceback <http://pastebin.com/t9a9amcR> (I printed it
from the the __lt__() method).

I think that this should be handled by pprint.py, however, it is tied to
the python version being used. Maybe pytest could handle this as a
workaround this limitation of pprint.py?

Fixing it in pprint.py looks straightforward: just handle it like repr.py
does, by using the _possiblysorted() method.

Thoughts?
​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pytest-dev/attachments/20150406/8c399391/attachment.html>


More information about the pytest-dev mailing list