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

如何将本地导入的函数作为pytest fixture使用?

解决pytest中批量导入函数的DRY实现问题

问题背景

我需要在测试中本地导入部分函数(已知代码架构可优化但无法调整),当前模块内所有测试函数的第一行均需执行from worker import process_message这类本地导入操作。为实现DRY原则,我编写了如下pytest fixture:

@pytest.fixture(scope="module", autouse=True)
def process_message():
    from worker import process_message
    return process_message

但运行时始终报错:

Fixture "process_message" called directly. Fixtures are not meant to be called directly, but are created automatically when test functions request them as parameters.

希望能实现批量导入,直接使用该函数句柄。

解决方案

报错核心原因是fixture名称与要导入的函数名完全重复,pytest会将测试代码中对process_message的引用识别为调用fixture,而非使用导入的业务函数。以下两种方案可解决问题:

方案一:全局变量自动导入(推荐)

修改fixture名称,同时在fixture中将导入的函数绑定到模块全局作用域,所有测试函数无需额外操作即可直接使用process_message:

import pytest

@pytest.fixture(scope="module", autouse=True)
def _import_process_message():
    global process_message
    from worker import process_message
  • scope="module"确保仅在模块初始化时导入一次,提升测试效率
  • autouse=True让fixture自动执行,无需在测试函数中声明依赖
  • 前缀下划线_避免fixture名称与业务函数冲突

方案二:fixture参数传递(显式控制场景)

若不想依赖全局变量,可修改fixture名称,在测试函数中通过参数接收函数句柄:

import pytest

@pytest.fixture(scope="module")
def process_message_func():
    from worker import process_message
    return process_message

# 测试函数示例
def test_process_message(process_message_func):
    result = process_message_func("test_data")
    assert result == expected_value

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 13:56:41