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

如何让pytest发现非规范命名测试及手动添加测试至发现列表?

pytest 测试发现问题解决方案

1. 强制发现指定测试

对于你提供的tests/test_assert.py中的测试函数,有两种直接可行的方式:

  • 直接指定运行:在命令行直接指定模块和函数名,跳过自动发现规则:

    pytest tests/test_assert.py::custom_assert
    
  • 通过标记筛选:利用函数上的@pytest.mark.mymark标记,筛选运行带该标记的测试:

    pytest -m mymark
    

2. 动态添加任意测试至发现列表

如果要让pytest自动发现不符合命名规范的测试,或者动态添加测试,可通过以下两种方法实现:

方法一:修改pytest配置文件

在项目根目录创建配置文件,自定义测试发现规则:

  • 使用pytest.ini:

    [pytest]
    python_files = test_*.py *.py
    python_classes = Test*
    python_functions = test_* custom_assert *assert*
    

    其中python_functions指定了要匹配的函数名模式,可添加任意需要发现的函数名或通配符。

  • 使用pyproject.toml:

    [tool.pytest.ini_options]
    python_files = ["test_*.py", "*.py"]
    python_classes = ["Test*"]
    python_functions = ["test_*", "custom_assert", "*assert*"]
    

方法二:自定义pytest钩子函数

在项目根目录创建conftest.py,通过pytest_collect_file钩子动态收集测试:

import pytest
from pytest import Function

def pytest_collect_file(parent, path):
    # 匹配目标文件
    if path.basename == "test_assert.py":
        # 导入目标模块
        module = parent.session._importpath(path)
        # 获取要添加的测试函数
        target_func = getattr(module, "custom_assert")
        # 创建测试项并返回,让pytest识别为测试
        return Function.from_parent(parent, name="custom_assert", obj=target_func)

这种方式灵活性极高,可根据文件路径、函数属性、标记等任意条件,将任意函数添加到pytest的测试发现列表中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:57:05