python config_error ai_generated true

PytestCollectionWarning: 无法收集测试类 'TestSession',因为它有 __init__ 构造函数

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

ID: python/pytest-collection-warning-coroutine

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

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 85% 失败

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

  2. 80% 失败

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