夹具函数不只是能写在conftest文件中在其他模块也能写但是使用范围和加载方式有所不同
夹具函数不只是能写在conftest文件中在其他模块也能写但是使用范围和加载方式有所不同。
1. 写在测试文件中
import pytest
@pytest.fixture
def user():
return {"name": "Tom"}
def test_user(user):
assert user["name"] == "Tom"
这种 fixture 一般只能被当前测试模块使用。
2. 写在 conftest.py 中
import pytest
@pytest.fixture
def user():
return {"name": "Tom"}
同目录测试可以直接使用,不需要导入:
def test_user(user):
assert user["name"] == "Tom"
conftest.py 中 fixture 的可见范围是:
tests/
├── conftest.py ← fixture
├── test_user.py ← 可以使用
└── api/
└── test_api.py ← 可以使用
也就是当前目录及其子目录中的测试通常都能使用。
但父目录或兄弟目录不能使用:
project/
├── module_a/
│ └── conftest.py ← fixture
└── module_b/
└── test_b.py ← 不能使用 module_a 中的 fixture
3. 写在普通 Python 模块中
例如:
# fixtures/user_fixtures.py
import pytest
@pytest.fixture
def user():
return {"name": "Tom"}
但 pytest 不会自动扫描任意普通模块。需要显式注册为插件,例如在 conftest.py 中:
pytest_plugins = [
"fixtures.user_fixtures",
]
测试才能直接使用:
def test_user(user):
assert user["name"] == "Tom"
也可以直接导入 fixture:
from fixtures.user_fixtures import user
不过对于共享 fixture,通常更推荐通过 pytest_plugins 注册。
4. 写在 pytest 插件中
第三方或项目自定义插件也可以提供 fixture。例如:
# my_pytest_plugin.py
import pytest
@pytest.fixture
def database():
return Database()
通过配置、命令行或 Python 包入口注册插件后,fixture 就可以被测试使用。
5. 写在测试类中
import pytest
class TestUser:
@pytest.fixture
def user(self):
return {"name": "Tom"}
def test_name(self, user):
assert user["name"] == "Tom"
这种 fixture 主要供当前测试类使用。
简单总结:
| 定义位置 | 大致可用范围 |
|---|---|
| 测试函数内部 | 不能作为标准 fixture 使用 |
| 测试类中 | 当前测试类 |
| 测试文件中 | 当前测试模块 |
conftest.py |
当前目录及子目录 |
| 普通 Python 模块 | 需要导入或注册成插件 |
| pytest 插件 | 加载插件的测试范围 |
最常见的选择是:
- 仅当前文件使用:写在测试文件。
- 多个测试文件共享:写在
conftest.py。 - 整个大型项目共享且 fixture 很多:拆到普通模块,再通过
pytest_plugins注册。

浙公网安备 33010602011771号