Skip to content

Improve diffs when comparing classes with repr #14231

@alexprengere

Description

@alexprengere

What's the problem this feature will solve?

I am a long-time user of pytest-clarity, and I see that some of its ideas were incorporated into core pytest, but there is one lacking feature that has proven really useful to me.

I am maintaining multiple large libraries with lots of classes, and I have many tests that basically amount to dumping class instances using custom serialization code, then loading them again and compare with the original instance. Those classes have a repr, and pytest-clarity shows a nice diff of the repr when the comparison fail.

Here is the basic reproducer.

class AC:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __repr__(self):
        return f"{self.__class__.__name__}({self.x}, {self.y})"


def test_class():
    a = AC(1, 1)
    b = AC(1, 2)
    assert a == b

Here is the visual output :

Image

For comparison here is the output when pytest-clarity is enabled:

Image

Mind that in a more realistic example, such classes can have dozens of attributes, which can themselves be classes with dozens of attributes, etc. The actual test may use libraries like hypothesis to find subtle bugs in the serialization/deserialization code.

So here would be my feature request: when pytest is showing both repr, highlighting the difference (akin to what is done to namedtuple, dataclasses, dicts) would be a great help!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions