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

Pytest遵循正确命名规范仍无法识别测试用例问题咨询

问题根因与修复方案

你的测试未被Pytest识别的核心原因是测试函数被错误标记为了夹具,另外还有几处代码逻辑问题需要同步修正:

1. 核心修复:移除测试函数上的夹具装饰器

Pytest会将添加了@pytest.fixture装饰器的函数识别为测试夹具,而非可执行的测试用例,直接删掉test_stop_word_removal上的@pytest.fixture(autouse=True)这一行即可解决测试不被识别的问题。

2. 修正夹具依赖逻辑

2.1 修复conftest.py中的夹具引用

Pytest的夹具不能直接调用,需要通过参数注入的方式引入依赖,修改load_spacy_model夹具的定义:

@pytest.fixture(scope="session")
# 把依赖的get_staticdata_path夹具作为参数传入,Pytest会自动注入值
def load_spacy_model(get_staticdata_path):
    model_path = get_staticdata_path / "en_core_web_sm"
    nlp = spacy.load(model_path)
    return nlp

2.2 测试函数中注入需要的夹具

你在测试中用到了load_spacy_model夹具,需要把它加到测试函数的参数列表中:

def test_stop_word_removal(text, expected, exception, monkeypatch, load_spacy_model):

3. 修正异常断言逻辑

当用例参数中exception为None时,pytest.raises(None)会直接报错,调整断言逻辑:

if exception is not None:
    with pytest.raises(exception):
        TextUtils.stop_word_removal(text)
else:
    result = TextUtils.stop_word_removal(text)
    assert result == expected

4. 检查Monkeypatch补丁写法

如果你要替换的是TextUtils类下的nlp属性,正确的补丁写法为:

monkeypatch.setattr(TextUtils, "nlp", load_spacy_model)

如果是替换stop_word_removal方法内部导入的nlp,确认补丁路径和实际导入路径一致即可。

验证方式

修改完成后执行以下命令,确认可以识别到对应测试用例:

pytest tests/natural_language_processing/test_utils.py -v

内容的提问来源于stack exchange,提问作者yudhiesh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:36:03