python config_error ai_generated true

PytestCollectionWarning: cannot collect test class 'TestSession' because it has a __init__ constructor

ID: python/pytest-collection-warning-coroutine

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-09-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

pytest collects any class named Test* but refuses classes with __init__. A domain class named TestSession (e.g., a SQLAlchemy model) collides with pytest's naming convention.

generic

中文

pytest 会收集任何以 Test* 命名的类,但拒绝有 __init__ 的类。名为 TestSession 的领域类(如 SQLAlchemy 模型)与 pytest 命名约定冲突。

Workarounds

  1. 96% success
    Set __test__ = False on the class:
    
    class TestSession(Base):
        __test__ = False
        __tablename__ = 'sessions'
  2. 90% success
    Or rename the class to avoid the Test prefix (e.g., SessionRecord).

Dead Ends

Common approaches that don't work:

  1. 85% fail

    pytest checks the class attribute before instantiation; instance attributes are never seen.

  2. 80% fail

    The model is imported transitively by many tests; the warning persists.