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
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.
解决方案
-
96% 成功率
Set __test__ = False on the class: class TestSession(Base): __test__ = False __tablename__ = 'sessions' -
90% 成功率
Or rename the class to avoid the Test prefix (e.g., SessionRecord).
无效尝试
常见但无效的做法:
-
85% 失败
pytest checks the class attribute before instantiation; instance attributes are never seen.
-
80% 失败
The model is imported transitively by many tests; the warning persists.