多个用例需要重复创建数据库连接、临时文件、HTTP 客户端或登录态;或者需要在测试结束后可靠清理资源。fixture 比 setUp、tearDown 更灵活,可以组合、参数化并控制作用域。
用 @pytest.fixture 装饰函数,测试函数把 fixture 名写成参数即可注入。作用域由小到大为 function(默认)、class、module、package、session;高作用域 fixture 不能依赖低作用域 fixture,否则报 ScopeMismatch。跨文件共享放进 conftest.py,pytest 会自动发现,不需要 import,且只对所在目录及子目录生效。
fixture 可以用 yield 把准备和清理写在一起:
@pytest.fixture
def resource():
obj = create_resource()
yield obj
obj.close()
yield 之前是 setup,之后是 teardown;测试失败时 teardown 仍会执行。多个 fixture 的清理顺序与创建顺序相反,依赖方先清理,被依赖方后清理。如果 setup 在 yield 之前就抛异常,yield 之后的代码不会执行;这种场景用 request.addfinalizer 注册清理。
factory fixture 不直接返回资源,而是返回一个创建资源的函数,让一个用例按需创建多份实例,并统一收集清理。
autouse=True 让 fixture 自动作用于当前作用域的每个测试,适合设置环境变量;副作用不明显的场景应显式注入,避免隐藏依赖。
常用内置 fixture:tmp_path 提供函数级临时目录,tmp_path_factory 提供会话级目录工厂,monkeypatch 临时修改环境变量和属性,capsys 捕获输出,request 访问参数、节点和终结器。
# conftest.py
import pytest
@pytest.fixture
def user():
data = {"name": "alice", "active": True}
yield data
data.clear()
# test_user.py
def test_user_active(user):
assert user["active"] is True
python -m pytest -q test_user.py
import pytest
@pytest.fixture
def make_file(tmp_path):
created = []
def _make(name, text):
path = tmp_path / name
path.write_text(text, encoding="utf-8")
created.append(path)
return path
yield _make
for path in created:
path.unlink(missing_ok=True)
def test_make_file(make_file):
path = make_file("a.txt", "hello")
assert path.read_text(encoding="utf-8") == "hello"
import sqlite3
import pytest
@pytest.fixture(scope="session")
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
yield conn
conn.close()
@pytest.fixture(autouse=True)
def test_env(monkeypatch):
monkeypatch.setenv("APP_ENV", "test")
def test_insert(db):
db.execute("INSERT INTO users (name) VALUES (?)", ("alice",))
assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1
session fixture 只创建一次,测试修改列表、字典或数据库行后,后面的测试会看到脏数据;只共享只读配置或连接,数据用 factory 每个测试新建。yield 之前的代码抛异常时,后面的 teardown 不会执行;已经打开的文件或连接要用 request.addfinalizer 兜底。session fixture 请求函数级 tmp_path 或 monkeypatch 会报 ScopeMismatch;改用 tmp_path_factory 或把 fixture 降为函数级。pytest-asyncio 的 @pytest_asyncio.fixture 或 AnyIO 支持;普通 @pytest.fixture 返回的是协程对象,不是结果。session 后有什么代价?yield 之前的 setup 失败时,写在 yield 之后的清理可能不执行?function;改为 session 后只创建一次,但共享可变状态可能污染后续测试。yield 才会登记后续 teardown;setup 提前抛异常时,后面的代码不会运行。
小程序版
微信扫码,随时查命令