python type_error ai_generated true

AssertionError: assert <myapp.models.User object at 0x7f8b1c0d5e50> == <myapp.models.User object at 0x7f8b1c0d5e50> E AttributeError: 'User' object has no attribute '__eq__'

ID: python/pytest-assertion-rewrite-cache-stale

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-05-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.10 active — — —
3.12 active — — —

Root Cause

The assertion compares two objects without __eq__ defined, so identity comparison fails. The confusing part is that pytest's assertion rewrite shows the repr, making it look like they should be equal.

generic

中文

断言比较两个未定义 __eq__ 的对象,因此身份比较失败。令人困惑的是 pytest 的断言重写会显示 repr,使其看起来应该相等。

Workarounds

  1. 95% success
    class User:
        def __init__(self, id):
            self.id = id
        def __eq__(self, other):
            return isinstance(other, User) and self.id == other.id
  2. 90% success
    assert result.id == expected.id
    assert result.name == expected.name

Dead Ends

Common approaches that don't work:

  1. 70% fail

    id() comparison only checks identity; if the test intends value equality, this is a false pass.

  2. 80% fail

    Same identity semantics; does not fix the missing __eq__ for value comparison.