python type_error ai_generated true

AssertionError: assert <myapp.models.User object at 0x7f8b1c0d5e50> == <myapp.models.User object at 0x7f8b1c0d5e50> E AttributeError: 'User' 对象没有属性 '__eq__'

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

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-05-22首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.10 active — — —
3.12 active — — —

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 80% 失败

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