Skip to content

Assert statements in Enum subclass definitions case errors when assertion rewriting is enabled #9582

Description

@finite-state-machine

While running pytest with the following code:

from enum import Enum

STEP = 100

class SomeEnum(Enum):

    FIRST = 100
    SECOND = FIRST + STEP
    THIRD = SECOND + STEP

    assert THIRD == 300

...assertion rewriting causes an error because of an interaction with Enum:

================================ test session starts ================================
platform darwin -- Python 3.8.12, pytest-6.2.5, py-1.9.0, pluggy-0.13.1
rootdir: /private/tmp/pytest-enum-assert-bug
plugins: profiling-1.7.0, order-1.0.1, cov-3.0.0
collected 0 items / 1 error

====================================== ERRORS =======================================
______________________________ ERROR collecting bug.py ______________________________
bug.py:5: in <module>
    class SomeEnum(Enum):
bug.py:11: in SomeEnum
    assert THIRD == 300
/Users/dsuffling/.pyenv/versions/3.8.12/lib/python3.8/enum.py:112: in __setitem__
    raise TypeError('Attempted to reuse key: %r' % key)
E   TypeError: Attempted to reuse key: '@py_assert1'
============================== short test summary info ==============================
ERROR bug.py - TypeError: Attempted to reuse key: '@py_assert1'
!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!
================================= 1 error in 0.28s ==================================

This error does not occur with --assert=plain:

================================ test session starts ================================
platform darwin -- Python 3.8.12, pytest-6.2.5, py-1.9.0, pluggy-0.13.1
rootdir: /private/tmp/pytest-enum-assert-bug
plugins: profiling-1.7.0, order-1.0.1, cov-3.0.0
collected 0 items

=============================== no tests ran in 0.02s ===============================

In fact, the issue can be reproduced by:

from enum import Enum

class SomeEnum(Enum):
    assert True

Environment:

pytest version: 6.2.5
environment: macOS 10.14, homebrew 3.3.12, pyenv 2.2.3, CPython 3.8.12
pip list (new virtualenv; nothing but pytest installed):

Package    Version
---------- -------
attrs      21.4.0
iniconfig  1.1.1
packaging  21.3
pip        21.1.1
pluggy     1.0.0
py         1.11.0
pyparsing  3.0.7
pytest     6.2.5
setuptools 56.0.0
toml       0.10.2

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: rewriterelated to the assertion rewrite mechanismtype: 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