装饰器 · pytest.fixture

0. 一句话定位

维度 内容
作用对象 函数
使用场景 测试
来源 第三方 pytest
语法形式 @pytest.fixture / @pytest.fixture(scope="module")

1. 做什么

把函数注册为 fixture:测试用例通过同名参数声明依赖,pytest 在运行测试前调用 fixture 并把返回值注入;支持 yield 做 teardown,支持 scope 控制复用范围。

2. 重点参数

参数 类型 默认值 作用 配置建议
scope str "function" 生命周期:function/class/module/package/session DB 连接常用 module;昂贵资源用 session
params list None 参数化 fixture,测试对每个值跑一遍 多组输入数据
autouse bool False 自动注入所有测试,无需显式参数 全局 mock、临时目录
name str 函数名 fixture 对外名称 与参数名不一致时指定
ids list/callable 自动 参数化时的用例 id 报告可读性

3. 最小可运行示例

conftest.py 或测试文件:

1
2
3
4
5
6
7
8
import pytest

@pytest.fixture
def sample_user():
return {"id": 1, "name": "alice"}

def test_user_name(sample_user):
assert sample_user["name"] == "alice"

yield teardown

1
2
3
4
5
6
7
8
@pytest.fixture
def temp_file(tmp_path):
p = tmp_path / "data.txt"
p.write_text("hello")
yield p
# teardown(可选)
if p.exists():
p.unlink()

scope

1
2
3
4
5
@pytest.fixture(scope="module")
def db_conn():
conn = connect()
yield conn
conn.close()

4. 常见变体

fixture 依赖 fixture

1
2
3
@pytest.fixture
def api_client(sample_user):
return Client(user=sample_user)

内置 fixturetmp_pathmonkeypatchcapfd 等无需定义。

@pytest.fixture(params=[1, 2, 3]):同一测试跑多组 fixture 值。

5. 适用 / 不适用

适用

  • 测试共享 setup(DB、客户端、样例数据)
  • 需要可预测 teardown 的资源

不适用

  • 简单单测、无共享状态 → 直接写在测试里
  • 复杂全局状态 → 考虑 factory 或显式 helper

6. 易踩坑

  • 测试函数参数名必须与 fixture 名一致(或 name= 匹配)
  • scope="session" 的 mutable 对象勿跨测试污染,或每次返回副本
  • fixture 定义在 conftest.py 可对目录下所有测试可见
  • 异步测试用 @pytest_asyncio.fixture(pytest-asyncio 插件)

7. 近邻替代

替代 何时用
setUp/tearDown(unittest) 类级传统风格
@pytest.mark.parametrize 仅参数矩阵,无 setup 逻辑
@mock.patch 替换单个对象

8. 参考

-------------本文结束感谢您的阅读-------------