You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何消除Pytest收集警告:无法收集含__init__的'dict'测试类

消除PytestCollectionWarning警告的方法

警告原因

你的类型别名TestDataDict以Test开头,pytest会自动识别tests目录下以Test开头的类为测试类,而该别名是dict的类型别名,dict自带__init__构造方法,pytest无法收集带有自定义构造方法的测试类,因此抛出警告。

解决办法

方法1:修改类型别名名称

将类型别名的名字改为不以Test开头,避免被pytest误识别为测试类:

修改tests/common.py:

DataDict = dict[str, str]

更新tests/test_main.py的导入与使用(同时修正类型不匹配的问题):

import pytest
import myproject.main
from tests.common import DataDict

@pytest.fixture()
def get_dict() -> DataDict:
    dict_ = {'a': '1', 'b': '2'}  # 修正值类型为str,匹配类型别名定义
    return dict_

def test_add(get_dict: DataDict) -> None:
    dict_ = get_dict
    assert myproject.main.add(int(dict_['a']), int(dict_['b'])) == 3

方法2:重命名工具文件

把tests/common.py改名为tests/_common.py,pytest默认会忽略下划线开头的文件,不会对其进行测试收集,即使别名以Test开头也不会触发警告。

方法3:明确标注类型别名(Python 3.10+)

使用typing.TypeAlias明确标记这是类型别名,帮助pytest识别它不是测试类:

修改tests/common.py:

from typing import TypeAlias

TestDataDict: TypeAlias = dict[str, str]

内容的提问来源于stack exchange,提问作者Håkon Hægland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 20:33:34