Skip to content

Assertion diffs print-outs break on dataclasses with InitVar fields #9820

Closed
@ajyoon

Description

@ajyoon

When an assertion fails comparing dataclasses which has InitVar fields, the diff printing function fails with an AttributeError as it attempts to access the InitVar field. InitVar fields are not actually attributes stored in the dataclass, and I believe pytest needs to inspect the type here as dataclass does to ensure it's not treated as a real attribute.

Complete example:

from dataclasses import InitVar, dataclass

@dataclass
class Foo:
    init_only: InitVar[int]
    real_attr: int


def test_demonstrate():
    assert Foo(1, 2) == Foo(1, 3)

Gives this error:

___________________________________________ test_demonstrate ___________________________________________
def test_demonstrate():
>       assert Foo(1, 2) == Foo(1, 3)
E       AssertionError: assert Foo(real_attr=2) == Foo(real_attr=3)
E         (pytest_assertion plugin: representation of details failed: /home/ayoon/.cache/pypoetry/virtualenvs/neoscore-ptOHLkol-py3.10/lib/python3.10/site-packages/_pytest/assertion/util.py:454: AttributeError: 'Foo' object has no attribute 'init_only'.
E          Probably an object has a faulty __repr__.)

I'm running on Python 3.10.2, and my reproduction environment's pip list gives:

(.venv) pytest_bug $ pip list
Package    Version
---------- -------
attrs      21.4.0
iniconfig  1.1.1
packaging  21.3
pip        21.3.1
pluggy     1.0.0
py         1.11.0
pyparsing  3.0.7
pytest     7.1.1
setuptools 60.9.3
tomli      2.0.1
wheel      0.37.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: help wanteddevelopers would like help from experts on this topictopic: reportingrelated to terminal output and user-facing messages and errorstype: bugproblem that needs to be addressed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions