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

pytest fixture作用域的工作机制及跨模块使用是否需导入?

关于pytest跨模块复用fixture是否需要显式导入的疑问

我想用pytest fixtures准备一个可在多组测试中复用的对象,按照官方文档设置了作用域为session的fixture,代码如下:

在something_fixture.py中:

import pytest

@pytest.fixture(scope="session")
def something():
    return 'something'

在test_something.py中直接使用该fixture时测试无法运行:

def test_something(something):
    assert something == 'something'

但显式导入fixture后测试就能通过:

from tests.something_fixture import something

def test_something(something):
    assert something == 'something'

我想知道这种导入操作是否是必须的?官方文档对此说明不够清晰。


答案

显式导入不是必须的,这只是复用fixture的方式之一。更推荐的做法是把fixture放到conftest.py文件中——pytest会自动识别这个文件里的fixture,不需要在测试文件中手动导入,就能直接在测试函数中使用。

举个例子:

  1. 在测试目录下创建conftest.py,写入fixture代码:
import pytest

@pytest.fixture(scope="session")
def something():
    return 'something'
  1. 直接在test_something.py中使用fixture即可:
def test_something(something):
    assert something == 'something'

如果不想用conftest.py,而是把fixture放在自定义的模块里,那确实需要显式导入,或者通过pytest_plugins配置来让pytest自动发现这些fixture。比如在测试目录的__init__.py中添加:

pytest_plugins = ["tests.something_fixture"]

这样也不需要在测试文件中手动导入fixture。

总结:

  • 用conftest.py是最简便的跨模块复用fixture的方式,无需导入
  • 自定义模块存放fixture时,要么显式导入,要么通过pytest_plugins配置自动发现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:26:28